NSTextField check if first responder without notification?

In iOS you can use textFieldName.isFirstResponder and it tells you if the control has focus.


Is there a way on macOS Cocoa to check which NSTextField has the current focus? .isFirstResponder is not available.


```

if nsTextFieldCity.isFirstResponder == true {

// Run Code

}

```


Thank you.

You can do it something like this:


if let window = nsTextFieldCity.window, window.firstResponder == nsTextFieldCity {
     // run code
}

Thanks, I tried that but the window.firstResponder is always the first field in the NSView. Any ideas? I am trying to find out which field has the current focus.


I appreciate it.

There really isn't anything else. If you have a view with multiple text fields (for example), then window.firstResponder must be the text field that has the flashing cursor (or the active selection). Perhaps you mean something else by "focus"?

By focus I mean the text field the user is currently typing in. This particular window has about 30 text fields that I need to know which field has the focus isFirstResponder in order to do calculations correctly.


Thanks.

My point was that you cannot type in a text file unless it is first responder. You're going to have to look into this a bit more carefully.


With macOS apps, there is one pitfall that sometimes trips up developers new to the platform. It's not that difficult to end up creating 2 windows where you meant to have only one. You don't know that you have two, because one is not shown, or because one is exactly on top of the other. In such cases, you get this sort of paradoxical behavior, where an action in the UI can't be "seen" in the code.


I have no particular reason to think you've run into this issue, but you're going to need to poke around with the debugger and/or add debugging code. Just make sure you check your assumptions, when you're trying to figure out what went wrong.

You should be checking for the NSTextField's field editor, because NSTextFields don't become the window's firstResponder even when they have focus (one of the quirks of AppKit). Search about the field editor.

To check if a text field is being edited try using currentEditor property instead like this:

Code Block
if (someTextField.currentEditor != nil)
{
//editing
}
else
{
//not editing...
}


NSTextField check if first responder without notification?
 
 
Q