这个问题可能存在于 Objective-c 中一个 6 岁的帖子中。我没有找到最近的答案或问题,或者用 Swift 编写的。
我正在使用情节提要,并且已将NSTextField
. 出于某种原因,当我单击该字段时,会显示占位符,当我输入文本并单击退出时,文本会消失。文本实际上在那里,因为当我重新点击时,输入的文本仍然存在。图层覆盖文本值似乎是某种类型的渲染问题?很奇怪。我正在使用NSTrackingArea
并添加CALayer
.
这是我的代码:
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
}
}