Search code examples
swiftxcodemacoscocoanstextfield

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.");
}

Solution

  • 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.