第一种方法,使用它的委托UITextFieldDelegate中的方法textFieldShouldReturn:来关闭虚拟键盘。
在UITextField视图对象如birdNameInput所在的类中实现这个方法。
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if ((textField == self.birdNameInput) || (textField == self.locationInput)) {
[textField resignFirstResponder];
}
return YES;
}
第二种方法,将birdNameInput的属性中Return Key修改为done,再定义一个方法和Done键的Did End On Exit连接。通过轻击done键触发这个事件来关闭虚拟键盘。
定义的方法如下:
- (IBAction) textFieldDoneEditing:(id)sender
{
[sender resignFirstResponder];
}
第三种方法,通过轻击键盘之外的空白区域关闭虚拟键盘。
在birdNameInput所属的视图控制器类的viewDidLoad方法中定义一个UITapGestureRecognizer的对象,然后将它赋值为它的视图。
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
[self.view addGestureRecognizer:tap];
定义选择器调用的方法dismissKeyboard。
-(void)dismissKeyboard {
[birdNameInput resignFirstResponder];
}
//注册通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
#pragma mark - 键盘将要隐藏
- (void)keyboardWillHide:(NSNotification *)notification
{
NSDictionary *userInfo = [notification userInfo];
NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSTimeInterval animationDuration;
[animationDurationValue getValue:&animationDuration];
[UIView animateWithDuration:animationDuration animations:^{
//TODO
}];
}