关于文本更改的Swift macOS通知
在我的NSViewController中,我有一个NSTexField,每当其内容更改时都会触发通知 我还有几个按钮,这些按钮定义了iAction来将字符写入NSTextField。 但是,每次按下其中一个按钮时,NSTEXT字段都会更新。通知未被激发 如何手动触发NSControlTextDidChange事件关于文本更改的Swift macOS通知,swift,macos,nsnotification,Swift,Macos,Nsnotification,在我的NSViewController中,我有一个NSTexField,每当其内容更改时都会触发通知 我还有几个按钮,这些按钮定义了iAction来将字符写入NSTextField。 但是,每次按下其中一个按钮时,NSTEXT字段都会更新。通知未被激发 如何手动触发NSControlTextDidChange事件 override func controlTextDidChange(_ notification: Notification) { if let textField = no
override func controlTextDidChange(_ notification: Notification) {
if let textField = notification.object as? NSTextField {
filterTable(with: textField.stringValue)
}
}
@IBAction func pressedKeyButton(_ sender: NSButton) {
let character = sender.title
self.searchTextField.stringValue.append(character)
self.searchTextField.textDidChange(Notification(name: .NSControlTextDidChange,object: nil))
}
由于这是一个Mac应用程序,您可以通过使用Cocoa绑定来填充文本字段,从而简化此过程。只需使用
didSet
块在视图控制器上声明dynamic
属性,如下所示:
@objc dynamic var searchString: String = "" {
didSet { /* put notification code here */ }
}
然后,在Interface Builder中的绑定检查器中,将文本字段的
值
绑定到视图控制器,并将“模型键路径”设置为搜索字符串
。此外,选中“持续更新值”复选框。在您自己的代码中,通过更改searchString
属性来更新文本字段,而不是直接访问文本字段(您甚至可以去掉文本字段的出口,因为您可能不再需要它)。由于文本字段中显示的字符串的所有更改现在都将通过searchString
属性进行,因此它的didSet
块将始终被调用,并且您将得到一致的通知。什么是“self.searchTextField.textdichange(通知(名称:.NSControlTextDidChange,对象:nil))?您的controlTextDidChange似乎也不正确。当触发pressedKeyButton操作时,NSTEX字段的内容会更新,但controlTextDidChange功能不会触发。