swift – NSTextField在子类化后淡出

前端之家收集整理的这篇文章主要介绍了swift – NSTextField在子类化后淡出前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用以下代码将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方法绘制视图而不是设置属性.对于你的问题,不要设置为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
    }

}

猜你在找的Swift相关文章