2017-08-05 120 views
0

我對swift很陌生, 我試圖以編程方式重置NSSearchField,但我沒有找到正確的方法來做到這一點! 目前我在做這樣swift osx NSSearchField以編程方式重置

import Cocoa 

extension NSSearchField { 
    func reset() { 
     self.stringValue = "" 
     let cell = self.cell as? NSSearchFieldCell 
     let cancelButton = cell?.cancelButtonCell 
     cancelButton?.performClick(self) 
    } 

} 

編輯: 我的問題是,在NSSearchFieldDelegate功能controlTextDidChange不叫。

如何打電話來做到這一點? 感謝

+0

會發生什麼? – adev

+0

我不知道你在做什麼。爲什麼你甚至需要爲NSSearchField寫一個緊張?讓cancelButton = cell?.cancelButtonCell? –

+0

@adev這將清空searchField中的textView – justBorn

回答

0

設置您的委託,否則controlTextDidChange不會被調用

您的擴展是沒問題的。

這裏有一個例子,當你做`self.stringValue = 「」`

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) 
} 
} 
相關問題