【发布时间】: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