问题
I'm a newbie developing for iOS devices. I inserted an UITextField on InterfaceBuilder, and I assigned with the code:
@interface ComposeViewController : UIViewController {
id <ComposeViewControllerDelegate> delegate;
IBOutlet UITextField *notificationTitle;
}
How I could allow to close the keyboard when the user press the "Return" key?
回答1:
Set the Delegate of the UITextField to your ViewController, add a referencing outlet between the File's Owner and the UITextField, then implement this method:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if (textField == yourTextField) {
[textField resignFirstResponder];
}
return NO;
}
回答2:
Inherit UITextFieldDelegate protocol In viewDidLoad method set:
yourTextField.delegate = self
Implement the delegate method below:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[yourTextField resignFirstResponder];
return NO;
}
回答3:
Inherit UITextFieldDelegate
protocol and implement textFieldShouldReturn:
, that's you will catch "return" event.
Inside textFieldShouldReturn
write [notificationTitle resignFirstResponder];
回答4:
Add a action target to the event Did End on Exit(UIControlEventEditingDidEndOnExit), in the target function remove the first responder from the text filed using resignFirstResponder. Adding action target
Note: 1. Nib --- give action to even Did End on Exit 2. In code add target action to the event UIControlEventEditingDidEndOnExit.
来源:https://stackoverflow.com/questions/4761648/close-the-keyboard-on-uitextfield