这个问题可能存在于 Objective-c 的一篇 6 年前的帖子中。我还没有找到最近有效的答案或问题,或者是用 Swift 编写的答案或问题。
我正在使用故事板并且我已经子类化NSTextField
。由于某种原因,当我单击该字段时,占位符会显示,当我输入文本并单击时,文本会消失。文本实际上在那里,因为当我单击返回时,输入的文本仍然存在。图层覆盖文本值似乎是某种类型的渲染问题?很奇怪。我在用着NSTrackingArea
并且还添加CALayer
.
Here's a screenshot of what happens:
这是我的代码:
class NowTextField: NSTextField {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// required nonsense
let textFieldLayer = CALayer()
let textFieldRect = NSRect(x: 0, y: 0, width: 120, height: 32)
let textFieldTrackingArea = NSTrackingArea.init(rect: textFieldRect, options: [NSTrackingAreaOptions.activeInActiveApp, NSTrackingAreaOptions.mouseEnteredAndExited], owner: self, userInfo: nil)
self.wantsLayer = true
self.layer = textFieldLayer
self.addTrackingArea(textFieldTrackingArea)
// styling
self.textColor = NSColor.darkGray
self.layer?.cornerRadius = 4
self.layer?.backgroundColor = NSColor.white.cgColor
self.layer?.borderColor = NSColor.lightGray.cgColor
self.layer?.borderWidth = 2
self.drawsBackground = false
}
override func mouseEntered(with event: NSEvent) {
self.textColor = NSColor.darkGray
self.layer?.cornerRadius = 4
self.layer?.backgroundColor = NSColor.white.cgColor
self.layer?.borderColor = NSColor.highlightBlue.cgColor
self.layer?.borderWidth = 2
self.drawsBackground = false
}
override func mouseExited(with event: NSEvent) {
self.textColor = NSColor.darkGray
self.layer?.cornerRadius = 4
self.layer?.backgroundColor = NSColor.white.cgColor
self.layer?.borderColor = NSColor.lightGray.cgColor
self.layer?.borderWidth = 2
self.drawsBackground = false
}
}
我找到了答案。我删掉了let textFieldLayer = CALayer()
也self.layer = textFieldLayer
因为这些似乎在文本字段的顶部添加了不必要的层。这是我的工作版本的完整代码:
class NowTextField: NSTextField {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// required nonsense
let textFieldRect = NSRect(x: 0, y: 0, width: 120, height: 32)
let textFieldTrackingArea = NSTrackingArea.init(rect: textFieldRect, options: [NSTrackingAreaOptions.activeInActiveApp, NSTrackingAreaOptions.mouseEnteredAndExited], owner: self, userInfo: nil)
self.wantsLayer = true
self.addTrackingArea(textFieldTrackingArea)
// styling
self.textColor = NSColor.darkGray
self.layer?.cornerRadius = 4
self.layer?.backgroundColor = NSColor.white.cgColor
self.layer?.borderColor = NSColor.lightGray.cgColor
self.layer?.borderWidth = 2
self.drawsBackground = false
}
override func mouseEntered(with event: NSEvent) {
self.textColor = NSColor.darkGray
self.layer?.cornerRadius = 4
self.layer?.backgroundColor = NSColor.white.cgColor
self.layer?.borderColor = NSColor.highlightBlue.cgColor
self.layer?.borderWidth = 2
self.drawsBackground = false
}
override func mouseExited(with event: NSEvent) {
self.textColor = NSColor.darkGray
self.layer?.cornerRadius = 4
self.layer?.backgroundColor = NSColor.white.cgColor
self.layer?.borderColor = NSColor.lightGray.cgColor
self.layer?.borderWidth = 2
self.drawsBackground = false
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)