【问题标题】:Execute callback when text changes inside a NSTextField in Swift当文本在 Swift 中的 NSTextField 内发生更改时执行回调
【发布时间】:2015-09-03 13:24:27
【问题描述】:

我有一个 NSTextField,我想在其中的文本发生变化时执行回调。回调是在表单底部启用禁用的“保存”按钮。

到目前为止,我设法做的是子类 NSTextView 以覆盖textDidChange(notification)

import Cocoa

class MyTextField: NSTextField {

    override func textDidChange(notification: NSNotification) {
        super.textDidChange(notification)
    }

}

在那之后,我没有设法在我的ViewController 中执行函数。我尝试使用NSNotificationCenter 来触发某种全局事件,我可以像这样在ViewController 中捕获这些事件:

//MyTextField.swift

import Cocoa

class MyTextField: NSTextField {

    override func textDidChange(notification: NSNotification) {
        NSNotificationCenter.defaultCenter().postNotification(notification)
        super.textDidChange(notification)
    }

}


//ViewController.swift

import Cocoa

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "fieldTextDidChange:", name: "NSTextDidChangeNotification", object: nil)
    }
    override func viewDidAppear() {
        super.viewDidAppear()
    }

    func fieldTextDidChange(notification: NSNotification) {
        print(notification, appendNewline: true)
    }
}

但在字段内输入时出现运行时错误:Thread 1: EXC_BAD_ACCESS (code=2, address=0x7fff5f3fff70) 在调用 postNotification() 的行上

如何在 NSTextField 的文本更改时触发回调?

编辑

正如 matt 所指出的,子类化和发送通知是愚蠢的。无需对文本字段进行子类化。只需观察NSTextDidChangeNotification 就足以对我正在寻找的事件做出反应。 我已经对此进行了测试,但我在选择器末尾缺少一个冒号,所以我认为这不是正确的方法。确实是正确的方法。

【问题讨论】:

  • 不需要继承NSTextField。将 Interface Builder 中的委托属性连接到适当的类并覆盖 controlTextDidDidChange - - override func controlTextDidChange(notification : NSNotification) { let textField = notification.object as! NSTextField }
  • 我没有测试过你的解决方案,因为我可以用通知中心来做,但听起来它也可以工作。在我的例子中(使用NSTextDidChangeNotification),通知中传递的对象引用是NSTextField 中的NSTextView。我必须获得超级视图的超级视图才能到达 NSTextField。
  • 它可以 - 它可以;-)

标签: macos swift cocoa nstextfield


【解决方案1】:

您崩溃的原因是您的selector 错误。应该是selector: "fieldTextDidChange:"(注意最后的冒号)。

【讨论】:

  • 但总的来说,您的代码非常愚蠢。你为什么要发布通知以响应收到通知???只需在您想要的地方收到一次。否则你就有可能在那个地方收到它两次
  • 这实际上是正确的。当我去掉postNotification 部分时,我所有的击键都加倍了。我删除了postNotification 行并将我的视图改回正常的NSTextView,现在我可以正常收听通知了。谢谢 !主要问题是选择器末尾缺少冒号。
猜你喜欢
  • 1970-01-01
  • 2014-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-25
相关资源
最近更新 更多