我对 swift 很陌生, 我正在尝试以编程方式重置 NSSearchField,但我没有找到正确的方法来执行此操作! 目前我正在以这种方式做
import Cocoa
extension NSSearchField {
func reset() {
self.stringValue = ""
let cell = self.cell as? NSSearchFieldCell
let cancelButton = cell?.cancelButtonCell
cancelButton?.performClick(self)
}
}
编辑: 我的问题是在NSSearchFieldDelegate中没有调用函数controlTextDidChange。
怎么打电话呢? 谢谢
设置你的委托,否则不会调用controlTextDidChange:
您的扩展不是问题。
这里有一个例子,
class ViewController: NSViewController, NSSearchFieldDelegate {
// Search Field
@IBOutlet weak var mySearchField: NSSearchField!
override func viewDidLoad() {
super.viewDidLoad()
// Don't forget to set delegate
self.mySearchField.delegate = self
}
// Driver program
@IBAction func onPress(_ sender: Any) {
// clear search field
self.mySearchField.reset()
}
// View output
override func controlTextDidChange(_ obj: Notification) {
print("--");
}
}
extension NSSearchField {
func reset() {
self.stringValue = ""
//let cell = self.cell as? NSSearchFieldCell
//let cancelButton = cell?.cancelButtonCell
//cancelButton?.performClick(self)
}
}