【问题标题】:Change NSTextField border and BG color while editing编辑时更改 NSTextField 边框和 BG 颜色
【发布时间】:2015-06-16 05:58:18
【问题描述】:

我有一个NSTextField,它在显示时不使用边框和窗口背景颜色,但我希望它在编辑时更改为默认边框和白色背景颜色。我知道我可以通过以下方式更改这些属性:

nameTextField.bezeled = true
nameTextField.backgroundColor = NSColor.textBackgroundColor()

我不知道如何在文本字段开始编辑和结束时收到通知。对此似乎没有任何行动。有没有其他方法可以实现这种行为?

编辑: 实际上,当将操作设置为“结束编辑时发送”时,可以通过文本字段的更改操作检测到编辑结束,这样就解决了,但我仍然如何检测开始编辑?

【问题讨论】:

    标签: macos swift cocoa nstextfield


    【解决方案1】:

    你可以设置delegateNSTextField

    nameTextField.delegate = self
    

    然后你可以设置不同的状态:

    func control(control: NSControl, textShouldBeginEditing fieldEditor: NSText) -> Bool {
        nameTextField.bezeled = true
        nameTextField.backgroundColor = NSColor.textBackgroundColor()
    
        return true
    }
    func control(control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool {
        nameTextField.bezeled = false
        nameTextField.backgroundColor = NSColor.windowBackgroundColor()
    
        return true
    }
    

    编辑:

    我认为您可以继承 NSTextField 并覆盖 becomeFirstResponderresignFirstResponder,然后您就知道 NSTextField 是否具有焦点。

    【讨论】:

    • 好的,谢谢,但问题是它们只有在文本实际更改时才会被调用。
    • 你也可以看看windowfirstResponder是不是NSTextField
    • 重写 firstReponder 方法使其工作,感谢您的帮助!我注意到的是,nameTextField.bezeled = true/false 在被覆盖的方法中使用时实际上不起作用(在委托方法中也没有)。正如我在 IB 中设置的那样,它不会改变为有边框并且只是没有边框。
    • 这篇文章可能对你有用:stackoverflow.com/questions/18568054/…
    • 感谢您的链接!尽管如此,为了这个简单的目的,不得不用贝塞尔曲线重新绘制整个边界还是有点过分了。
    猜你喜欢
    • 2013-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    相关资源
    最近更新 更多