NSTextField enter key detection or firstResponder detection

与世无争的帅哥 提交于 2019-11-30 17:03:33

问题


I have two NSTextFields: textFieldUserID and textFieldPassword.

For textFieldPassword, I have a delegate as follows:

- (void)controlTextDidEndEditing:(NSNotification *)aNotification

This delegate gets called when textFieldPassword has focus and I hit the enter key. This is exactly what I want.

My problem is that controlTextDidEndEditing also gets called when textFieldPassword has focus and I move the focus to textFieldUserID (via mouse or tab key). This is NOT what I want.

I tried using controlTextDidChange notification (which is getting called once per key press) but I was unable to figure out how to detect enter key ( [textFieldPassword stringValue] does not include the enter key). Can someone please help me figure this one out?

I also tried to detect if textFieldUserID was a firstResponder, but it did not work for me. Here is the code I tried out:

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

I sure could use some help here!


回答1:


If I understood you correctly, you could set an action for the password text field and tell the field to send its action only when the user types Return. Firstly, declare and implement an action in the class responsible for the behaviour when the user types Return on the password field. For example:

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

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

Making the text field send its action on Return only, and linking the action to a given IBAction and target, can be done either in Interface Builder or programatically.

In Interface Builder, use the Attributes Inspector, choose Action: Sent on Enter Only, and then link the text field action to an IBAction in the object that implements it, potentially the File’s Owner or the First Responder.

If you’d rather do it programatically, then:

// 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];



回答2:


[passwordTextFieldCell setTarget:self];

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

- (void) someAction{

//handle

}


来源:https://stackoverflow.com/questions/6289336/nstextfield-enter-key-detection-or-firstresponder-detection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!