退出键盘:
方法1:不使用代理,直接使用;
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.textField resignFirstResponder];
}
方法2:使用代理,通过点击键盘Return键收起键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
//textField放弃第一响应者 (收起键盘)
[textField resignFirstResponder];
return YES;
}
两种方法可以同时添加,还有几种方法:
这三种方法在调用时,也都可以退出键盘。
[self.view endEditing:YES]; [[[UIApplication sharedApplication] keyWindow] endEditing:YES]; [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
避免键盘弹出遮挡输入框:
方法1:自己代码集成。
在viewDidLoad中注册两个通知,监听键盘弹出和退出
//增加监听,当键盘出现或改变时收出消息 //增加监听,当键退出时收出消息 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//增加监听,当键退出时收出消息 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
- (void)keyboardWillShow:(NSNotification*)aNotification {
NSDictionary *info = [aNotification userInfo];
CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
//目标视图UITextField
CGRect frame = self.textField.frame;
int offsetY = frame.origin.y + frame.size.height - (self.view.frame.size.height - keyboardSize.height);
NSTimeInterval animationDuration = 0.30f;
[UIView beginAnimations:@"ResizeView" context:nil];
[UIView setAnimationDuration:animationDuration];
if(offsetY > 0)
{
self.view.frame = CGRectMake(0, -offsetY, self.view.frame.size.width, self.view.frame.size.height);
}
[UIView commitAnimations];
}
//键盘隐藏后将视图恢复到原始状态
-(void)keyboardWillHide:(NSNotification *)aNotification
{
NSTimeInterval animationDuration = 0.30f;
[UIView beginAnimations:@"ResizeView" context:nil];
[UIView setAnimationDuration:animationDuration];
self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
[UIView commitAnimations];
}
方法2:使用IQKeyboardManager: github地址: https://github.com/hackiftekhar/IQKeyboardManager
|