如何检查我是否已按下NSSearchField搜索按钮?nssearchfield的搜索按钮
@IBAction func searchTextField(_ sender: NSSearchField) {
if `searchButtonIsClicked` {
//Code if searchButtonIsClicked
return
}
if sender.stringValue != "" {
//My code
}
}
我需要做什么,而不是searchButtonIsClicked
?
这是解决方案。
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var searchFieldText: NSSearchField!
@IBOutlet weak var labelSearchText: NSTextField!
@IBAction func searchFieldButton(_ sender: NSSearchField) {
if searchFieldText.stringValue != "" {
//My code. For example:
labelSearchText.stringValue = searchFieldText.stringValue
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let cellMenu = NSMenu(title: "Search Menu")
var item: NSMenuItem!
item = NSMenuItem(title: "Clear", action: nil, keyEquivalent: "")
item.tag = Int(NSSearchFieldClearRecentsMenuItemTag)
cellMenu.insertItem(item, at: 0)
item = NSMenuItem.separator()
item.tag = Int(NSSearchFieldRecentsTitleMenuItemTag)
cellMenu.insertItem(item, at: 1)
item = NSMenuItem(title: "Recent Searches", action: nil, keyEquivalent: "")
item.tag = Int(NSSearchFieldRecentsTitleMenuItemTag)
cellMenu.insertItem(item, at: 2)
item = NSMenuItem(title: "Recents", action: nil, keyEquivalent: "")
item.tag = Int(NSSearchFieldRecentsMenuItemTag)
cellMenu.insertItem(item, at: 3)
searchFieldText.searchMenuTemplate = cellMenu
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
谢谢您的帮助。
我认为这个演示可以解决您的问题。
Swift代码如下:
if let cell = searchField.cell as? NSSearchFieldCell {
let searchButtonCell: NSButtonCell = cell.searchButtonCell!
let cacelButtonCell: NSButtonCell = cell.cancelButtonCell!
searchButtonCell.target = self
cacelButtonCell.target = self
searchButtonCell.action = #selector(clickSearchButton(_:))
cacelButtonCell.action = #selector(clickCacelButton(_:))
}