I have an macOS app using Xcode 11 for development and I have an @IBOutlet weak var searchTextField: NSSearchField! in my view controller class to filter a table view. Also, I have menu options for this search field. This code works fine. However, I would like to move this search function to the toolbar. So, I added a search toolbar item to the toolbar and CTRL-Draged it to the first responder and connected it to an @IBAction func. But I am at a loss of how to proceed. What are the steps required implement a search feature in the toolbar. Please advise.
1 Answers
0
votes
I got this from another user. It is exactly what I was looking for.
// ViewController.swift
// This assumes the search field is first in the toolbar
import Cocoa
class ViewController: NSViewController {
override func viewWillAppear() {
guard let toolbar = self.view.window?.toolbar else {
return
}
guard let searchFieldToolbarItem = toolbar.items.first else {
return
}
guard let searchField = searchFieldToolbarItem.view as? NSSearchField else {
return
}
searchField.target = self
searchField.action = #selector (procSearchFieldInput (sender:))
}
@objc func procSearchFieldInput (sender:NSSearchField) {
print ("\(#function): \(sender.stringValue)")
}
}
searchCustomer
? Do you use the outlet outside theNSSearchFieldDelegate
and search field action methods? – Willeke