3
votes

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
I personally do not know much a about Swift, however it might be because you're using view.window?. You might want to try using the name of your ViewController class, however once again I am very new to Swift. Also, I'm not too sure if I understand your question correctly. Maybe clarify how you want the NSTextField to be focused, what that means exactly?lucap
You should do resignFirstResponder() on your text viewLee
@Lee I've tried sender.window?.resignFirstResponder() but in vain ..Willjay
sender.resignFirstResponder()Leo Dabus
@LeoDabus not working as wellWilljay

3 Answers

3
votes

Just try this: change "view.window?" to "sender"

@IBAction func endOfEditing(sender: NSTextField) {
   sender.makeFirstResponder(nil)
   sender.resignFirstResponder()
}
2
votes

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

0
votes

try add this function to your viewController

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    // I assume your textField call myText
    myText. resignFirstResponder()
}