Domanda

I want to make a text field in which if I click out of it, or press enter, it makes it lose focus. As in the focus ring disappears. I've have seen situations like this, but I do not know where to place the code for it. Can anyone show me how to make the NSTextfield lose it's focus?

È stato utile?

Soluzione

One method would be to implement the NSTextFieldDelegate, assign the delegate to your text field, and have it call a selector (a method in your code that changes makes the first responder = nil). The delegate will be called with a message when the text field is finished receiving input. Check out the API here for more information:

https://developer.apple.com/library/mac/documentation/cocoa/reference/NSTextFieldDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intf/NSTextFieldDelegate

Altri suggerimenti

For people out there as lazy as me, here is some code.

This is the cut down NSTextfieldDelegate method i used:

func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool {
    DispatchQueue.main.async {
        self.textField2.window?.makeFirstResponder(nil)
    }
    return true
}

https://developer.apple.com/documentation/appkit/nstextview/1807135-resignfirstresponder?language=objc

resignFirstResponder Docu says the following:

Use the NSWindow method makeFirstResponder:, not this method, to make a text view the first responder. Never invoke this method directly.

// don't use this as the name may suggest (at least it did for me)
self.textField2.resignFirstResponder()
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top