【问题标题】:Change background colour of NSTextField when renaming using ReturnKey使用 ReturnKey 重命名时更改 NSTextField 的背景颜色
【发布时间】:2021-04-05 04:40:28
【问题描述】:

我有一个NSTextField,它的背景颜色设置为透明。

当我按下回车键时,文本字段进入编辑模式并开始将文件重命名为Xcode

这里我想把背景颜色改成白色。目前,我正在更改 controlTextDidBeginEditing(_ obj: Notification) 中的背景颜色,这是在文本字段接收到文本更改后调用的。

但是,我正在寻找一种可以在按下回车键后立即更改背景颜色的方法。

这是我当前的代码:

private class TextField: NSTextField, NSTextFieldDelegate {
    init() {
        super.init(frame: .zero)
        delegate = self
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func controlTextDidBeginEditing(_ obj: Notification) {
        let textField = obj.object as! NSTextField
        textField.backgroundColor = NSColor.textBackgroundColor
    }

    public func controlTextDidEndEditing(_ obj: Notification) {
        let textField = obj.object as! NSTextField
        textField.backgroundColor = NSColor.clear
    }
}

谢谢。

【问题讨论】:

  • 不要问controlTextDidBeginEditing(_:)能为你做什么。询问您可以使用 func doCommand(by aSelector: Selector!, command infoDictionary: [AnyHashable : Any]!) 做什么。
  • 谢谢 El,我试过这个方法,发现当文本字段结束编辑时它被调用(通过第二次按返回键)。
  • 恐怕我没听懂你说的。我只理解语法正确的英语句子。
  • 不用担心,谢谢:)。
  • 与问题无关,但您可以覆盖 textDidBeginEditing(_:)textDidEndEditing(_:),而不是让文本字段成为自己的代表。

标签: swift macos nstextfield


【解决方案1】:

如果我理解正确,您想在文本成为 firstResponder 时更改颜色(即当用户单击 textField 时)?如果是这样,我认为您应该使用 textShouldBeginEditing - func textShouldBeginEditing(_ textObject: NSText) -> Bool 和适当的 func control(_ control: NSControl, textShouldBeginEditing fieldEditor: NSText) -> Bool 函数。

如果我错过了理解,而您的实际意思是在用户单击弹出的键盘中的“输入”按钮后更改背景颜色 - 您希望在 textField 完成成为 firstResponder 后更改颜色。 在这种情况下,您应该使用textShouldEndEditingtextDidEndEditing 委托方法及其相应的控制方法 textShouldEndEditing textDidEndEditing

【讨论】:

  • 很遗憾,textShouldBeginEditingcontrol(_ control: NSControl, textShouldBeginEditing fieldEditor: NSText) 在接收到文本输入后也会被调用。
  • 按回车,我的意思是文本字段进入编辑模式并开始将文件重命名为 Xcode。如果我再按回车,它将退出编辑模式。
  • 有趣,你是对的 - 我不知道 macOS 上的这种行为......也许这会有所帮助 - stackoverflow.com/questions/55078226/…。除非使用@El Tomato 建议,否则我认为您将不得不创建一个新的 NSTextField 子类并使用 NSResponder 的鼠标功能来实现您想要的……或者使用扩展? developer.apple.com/documentation/appkit/nsresponder
  • 谢谢,感谢您的宝贵时间。编辑结束时也会调用doCommand
【解决方案2】:

看起来要覆盖的方法是 selectText(_ sender: Any?),当 NSTextField 成为FirstResponder 时立即调用它,因为默认情况下选择了文本。

override func selectText(_ sender: Any?) {
    let textField = sender as! NSTextField
    textField.backgroundColor = NSColor.textBackgroundColor
    super.selectText(sender)
}

public func controlTextDidEndEditing(_ obj: Notification) {
    let textField = obj.object as! NSTextField
    textField.backgroundColor = NSColor.clear
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-11
    • 2014-03-15
    • 1970-01-01
    • 2012-07-10
    • 2015-01-07
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多