I have two NSTextField
s: 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 textFieldUs开发者_StackOverflow中文版erID
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!
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];
[passwordTextFieldCell setTarget:self];
[passwordTextFieldCell setAction:@selector(someAction:)];
- (void) someAction{
//handle
}
精彩评论