cocoanssearchfield

Center placeholder string in NSSearchField after it was changed


I have a NSSearchField in UI with a placeholderString. By default its value is Search and it is centered automaticaly. But when user change selection in the sidebar I replace placeholder string with "Search in {NAME OF SIDEBARITEM}". For example:

enter image description here

As you can see placeholder string is not centered anymore. It will be centered after this search field activated and then deactivated.

Ho do I force NSSearchField to reposition placeholder string after it was changed?


Solution

  • The only working solution I fond is to set search field's stringValue to some non-empty value and then to previously set value like so right after placeholder was changes:

    @IBAction func setPlaceholder(sender: AnyObject) {
        self.searchField.placeholderString = self.inputField.stringValue
        let currentSearchStringValue = self.searchField.stringValue
        self.searchField.stringValue = "-"
        self.searchField.stringValue = currentSearchStringValue
    }