NSTextField Focus

Viewed 3213

How to remove focus on NSTextField if I'm not focus in the textField?

I have a NSTextField and I set the Action: Sent On End Editing. After clicking the textField, the FOCUS will always in my NSTextField when I click other places on the view. Furthermore, I use makeFirstResponder and resignFirstResponder but all in vain. Any idea?

@IBAction func endOfEditing(sender: NSTextField) {
    view.window?.makeFirstResponder(nil)
    view.window?.resignFirstResponder()
}

For illustration, the FOCUS will always be in textField no matter where I pressed. (Even when I pressed the button)

enter image description here

How can I remove the focus when I click outside the textField?

enter image description here

3 Answers

Swift 4

For those still troubling with focus and unfocus: I don't know if it was the case back in 2016, but in Swift 4 my NSTextField loses focus except if I click in another "selectable" outlet.

For instance if I click on a NSButton right after NSTextField it won't lost focus. I suspect the NSButton catches the event, preventing the textfield to know it has to unfocus.

Here is a much radical solution which will definitely defocus an NSTextField

@IBAction func clickMyButton(_ sender: NSButton) { // or anywhere else

    self.quantityTextField.isEnabled = false
    self.quantityTextField.isEnabled = true

}

Not very sexy but it is reliable

Edit: Just saw it, it solves @Lee's issue

Related