user3722523
user3722523

Reputation: 1790

How to determine the active textfield

How to determine which text field is active ? (which one have the focus on it).

I found this code in objective-C but don't know how if it is still working and how to translate it in swift

NSResponder *firstResponder = [[NSApp keyWindow] firstResponder];
    if ([firstResponder isKindOfClass:[NSText class]] && [(id)firstResponder delegate] == mySearchField) {
    NSLog(@"Yup.");
}

Upvotes: 0

Views: 2579

Answers (3)

Willeke
Willeke

Reputation: 15589

Here you go:

var responder = window.firstResponder
if responder.isKind(of: NSText.self) {
    let fieldEditor = responder as! NSText
    responder = fieldEditor.delegate as! NSResponder
}

At the end is responder the focused control. If the focused control is a NSTextField then the first responder is the field editor, a NSTextView inside the text field. The delegate of the field editor is the control.

Upvotes: 2

You can do an if else and iterate over each textField so you can know what textField is the firstResponder.

func methodForDiscoverTheFirstResponder {
    if myTextField.isFirstResponder {
        //do stuff
    } else if mySecondTextField.isFirstResponder {
        //do stuff
    }
    ...
}

Upvotes: -1

Josh Homann
Josh Homann

Reputation: 16327

Umm here is how I would do it in iOS if anyone is interested. I am not familiar with how Mac OS deals with firstResponder, but it looks to be quite different.

    func findFirstResponder(in view: UIView) -> UIView? {
        for subview in view.subviews {
            if subview.isFirstResponder {
                return subview
            }
            if let firstReponder = findFirstResponder(in: subview) {
                return firstReponder
            }
        }
        return nil
    }

Upvotes: 0

Related Questions