Search code examples
swiftcocoansimagenssearchfield

Change search field's icon


I try to implement search behavior like in Xcode: if you enter something in search field, icon changes color.

I delegate both searchFieldDidStartSearching and searchFieldDidEndSearching to controller and change the image. The problem is icon's image changes only when window lose it's focus.

enter image description here

class ViewController: NSViewController {
    @IBOutlet weak var searchField: NSSearchField!

    func searchFieldDidStartSearching(_ sender: NSSearchField) {
        print("\(#function)")

        (searchField.cell as! NSSearchFieldCell).searchButtonCell?.image = NSImage.init(named: "NSActionTemplate")
    }

    func searchFieldDidEndSearching(_ sender: NSSearchField) {
        print("\(#function)")

        (searchField.cell as! NSSearchFieldCell).searchButtonCell?.image = NSImage.init(named: "NSHomeTemplate")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }
}

Thanks in advance for any ideas/suggestions.


Solution

  • Solve problem by subclassing NSSearchFieldCell and assign this class to field's cell.