如何检查是否已按下NSSearchField的搜索按钮

时间:2017-06-06 20:22:52

标签: swift3 nssearchfield

如何检查我是否按下了NSSearchField搜索按钮? search button of NSSearchField

@IBAction func searchTextField(_ sender: NSSearchField) {
        if `searchButtonIsClicked`  {
            //Code if searchButtonIsClicked
            return
        }
        if sender.stringValue != ""  {
            //My code
        }
    }

我需要做什么而不是searchButtonIsClicked

2 个答案:

答案 0 :(得分:0)

这是解决方案。

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.
        }
    }
}

感谢您的帮助。

答案 1 :(得分:0)

我认为this demo可以解决您的问题。

下面的快捷代码:

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(_:))
    }