0
votes

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
Is the action of the search field in the view controller connected to an action of this view controller? To which action is the search field in the toolbar connected?Willeke
The search field that is in the view controller code is : IBOutlet weak var searchTextField: NSSearchField!". All the working code is using this field. The action for the toolbar search field action is IBAction func searchCustomer(_ obj: NSSearchField) { print("Search Selected") .. When I said first responder I meant first responder of the IB.Eagle
Which class implements searchCustomer? Do you use the outlet outside the NSSearchFieldDelegate and search field action methods?Willeke
Is the view controller the content view controller of the window?Willeke
Yes, the view controller is the content view controller for the window and it is in this class where I have the IBAction searchCustomer.Eagle

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)")
    }
}