NSTextField resigning first responder

2019-06-23 22:30发布

问题:

I'm trying to have my text field resign first responder when the user is done editing it, like when they hit enter. The delegate method is getting called but what I have now doesn't work, what is the proper way to go about doing this?

- (BOOL)control:(NSControl *)control textShouldEndEditing:(NSText *)fieldEditor
{
    [fieldEditor resignFirstResponder];
    return YES;
}

回答1:

From the docs on the -resignFirstResponder method:

Use the NSWindow makeFirstResponder: method, not this method, to make an object the first responder. Never invoke this method directly.

This code should do it:

[myWindow makeFirstResponder:nil];


回答2:

- (void)controlTextDidEndEditing:(NSNotification *)obj {

   [self.window makeFirstResponder:view];
}

where "view" is the parent NSView of your NSTextView control.



回答3:

I believe you are looking for the NSControl delegate method:

- (void)controlTextDidEndEditing:(NSNotification *)notif

Implement this method in your NSTextField delegate (easily set in IB).

Then your request to change the responder, such as

[self.window selectNextKeyView:self]

should work.



回答4:

I am no expert in iPhone programming yet but the method you need to implement is "textFieldShouldReturn" implemented like this:

  - (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    [theTextField resignFirstResponder];
    return YES;
}