Search code examples
swift3nssearchfield

NSSearchField delegate in Yosemite


I'm making a new Swift (3.0) framenwork which involves the use of a NSSearchField programmatically created, like the rest of the views. This framenwork has the deployment target set to 10.10 and I found strange being not able to set the delegate metods for it. In fact NSSearchFieldDelegate only appear availabe in 10.11 on.

class PlistEditor: NSObject, NSOutlineViewDelegate, NSOutlineViewDataSource, NSTextFieldDelegate, NSSearchFieldDelegate {
 var searchField : NSSearchField?
 // more code..
 init(tabItem: NSTabViewItem,
       plistPath: String?) {
        // more code..
        let sf = NSSearchField(frame: NSMakeRect(80, 0, 80, 22))
        self.searchField? = sf
        // more code..
        super.init()
        // more code..
        if #available(OSX 10.11, *) {
            self.searchField?.delegate = self
        } else {
            // Fallback on earlier versions

        }

        // more code
    }

}

Ok, I thought it was inherent from NStextField, and maybe I can access the cell and set up using the superclass delegate, but unfurtunately I cannot found a way to do that. What I need is to be able to receive NSText/NSTextField notification in 10.10. How can I do this? error received

plist editor vibrant

EDITED: added more info on how is made plus some picts


Solution

  • Without providing more info, i am guessing you forgot to declare that your class is conforming to the NSSearchFieldDelegate.

    See the example below, how to set it up for example a viewController. You just create an extension for your vc, and declare it to conform to the delegate.

    class SearchViewController: NSViewController {
        let searchField: NSSearchField? = NSSearchField(frame: .zero)
    
        override func viewWillAppear() {
            super.viewWillAppear()
            if #available(OSX 10.11, *) {
                self.searchField?.delegate = self
            } else {
                // Fallback on earlier versions
    
            }
        }
    }
    
    extension SearchViewController: NSSearchFieldDelegate {
        func searchFieldDidStartSearching(_ sender: NSSearchField) {
            print("didStart")
        }
    
        func searchFieldDidEndSearching(_ sender: NSSearchField) {
            print("didEnd")
        }
    }
    

    EDIT:
    To capture the textDidChange event in earlier versions of Mac OS, you need to subclass NSSearchField and override textDidChange function. Every time a change happens in the searchField, it will call the function for you.

    class DLSearchField: NSSearchField {
    
        override func textDidChange(_ notification: Notification) {
            Swift.print("textDidChange")
        }
    }