NSTextField 在子类化后淡出

NSTextField Fades Out After Subclassing

我使用以下代码对 NSTextField 进行了子类化:

import Cocoa

class CustomSearchField: NSTextField {
    override func draw(_ dirtyRect: NSRect) {
        self.wantsLayer = true
        let textFieldLayer = CALayer()
        self.layer = textFieldLayer
        self.backgroundColor = NSColor.white
        self.layer?.backgroundColor = CGColor.white
        self.layer?.borderColor = CGColor.white
        self.layer?.borderWidth = 0
        super.cell?.draw(withFrame: dirtyRect, in: self)
    }
}

class CustomSearchFieldCell: NSTextFieldCell {
    override func drawingRect(forBounds rect: NSRect) -> NSRect {
        let minimumHeight = self.cellSize(forBounds: rect).height
        let newRect = NSRect(x: rect.origin.x + 25, y: (rect.origin.y + (rect.height - minimumHeight) / 2) - 4, width: rect.size.width - 50, height: minimumHeight)

        return super.drawingRect(forBounds: newRect)
    }
}

一切正常,它按照我的意愿绘制了我的 NSTextField。唯一的问题是,一旦我将界面的其他部分设置为第一响应者(在 NSTextField 外部单击),NSTextField 内的文本(占位符或填充文本)就会淡出。一旦我再次点击它,它就会淡出。我一直在寻找安静的时间,但无法真正弄清楚为什么会这样。我只希望文本始终可见,而不是淡入淡出。

它与我添加的 CALayer 有关,它是为了完成我的样式。

每当我 运行 在文本字段上从 viewDidLoad 进行相同的设置时,它就像一个魅力。例如:

class ViewController: NSViewController {
    @IBOutlet weak var searchField: NSTextField!

    override func viewDidLoad() {
        initCustomSearchField()
    }

    private func initCustomSearchField() {
        searchField.wantsLayer = true
        let textFieldLayer = CALayer()
        searchField.layer = textFieldLayer
        searchField.backgroundColor = NSColor.white
        searchField.layer?.backgroundColor = CGColor.white
        searchField.layer?.borderColor = CGColor.white
        searchField.layer?.borderWidth = 0
        searchField.delegate = self
    }
}

draw 方法应该真正用于绘制视图不设置 properties.And 为您的问题不要设置 self.layer 直接使用 sublayer 代替。

我对您的代码的建议:

class CustomTextField :NSTextField {

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)

        setupView()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }

    func setupView(){
        textColor = .green
    }
}

class CustomTextFieldCell: NSTextFieldCell {

    override init(textCell string: String) {
        super.init(textCell: string)
        setupView()
    }

    required init(coder: NSCoder) {
        super.init(coder: coder)

        setupView()
    }

    func setupView(){
        backgroundColor = .red
    }


    override func drawingRect(forBounds rect: NSRect) -> NSRect {
        let newRect = NSRect(x: (rect.width - rect.width/2)/2, y: 0, width: rect.width/2, height: 20)
        return super.drawingRect(forBounds:newRect)
    }

    override func draw(withFrame cellFrame: NSRect, in controlView: NSView) {
        super.draw(withFrame: cellFrame, in: controlView)
        controlView.layer?.borderColor = NSColor.white.cgColor
        controlView.layer?.borderWidth = 2
    }

}