NSTextField introduces key detection or detection of the firstResponder

I have two NSTextFields: textFieldUserIDand textFieldPassword.

For textFieldPasswordI have a delegate as follows:

- (void)controlTextDidEndEditing:(NSNotification *)aNotification

This delegate is called when it textFieldPasswordhas focus, and I press the enter key. This is exactly what I want.

My problem is that it is controlTextDidEndEditingalso called when it textFieldPasswordhas focus, and I move the focus to textFieldUserID(using the mouse or the tab key). This is NOT what I want.

I tried to use a notification controlTextDidChange(which is called once to press a key), but I was not able to figure out how to detect the input key ( [textFieldPassword stringValue]does not include the input key). Can someone please help me figure this out?

I also tried to find out what I textFieldUserIDwas firstResponder, but that didn't work for me. Here is the code I tried:

if ( [[[self window] firstResponder] isKindOfClass:[NSTextView class]] &&
    [[self window] fieldEditor:NO forObject:nil] != nil ) {
    NSTextField *field = [[[self window] firstResponder] delegate];
    if (field == textFieldUserID) {
        // do something based upon first-responder status
        NSLog(@"is true");
    }
}

Of course I could help here!

+5
source share
2 answers

If you understand correctly, you can set an action for the password text field and tell the field to send its action only when the user types Return. First, declare and execute the action in the class responsible for the behavior when the user types Returnin a password field. For instance:

@interface SomeClass
- (IBAction)returnOnPasswordField:(id)sender;
@end

@implementation SomeClass
- (IBAction)returnOnPasswordField:(id)sender {
    // do something
}
@end

Bringing the text field to action only in Return, and the binding of the action to the specified IBActionand target object can be performed either in Interface Builder, or programmatically.

Interface Builder Attributes Inspector, Action: Sent on Enter Only, IBAction , , .

, :

// Make the text field send its action only when Return is pressed
[passwordTextFieldCell setSendsActionOnEndEditing:NO];

// The action selector according to the action defined in SomeClass
[passwordTextFieldCell setAction:@selector(returnOnPasswordField:)];

// someObject is the object that implements the action
[passwordTextFieldCell setTarget:someObject];
+14
[passwordTextFieldCell setTarget:self];

[passwordTextFieldCell setAction:@selector(someAction:)];

- (void) someAction{

//handle

}
0

All Articles