最近碰到一些关于键盘处理的问题 特地将这些问题整理出来 以后遇到新的问题再继续完善...
- 退出键盘的方式
- 让textField不成为第一响应者
[self.textField resignFirstResponder];
- 退出编辑模式
[self.view endEditing:YES];
- 让textField的位置随键盘改变而改变
- 可以通过通知实现
-(void)viewDidLoad{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
-(void)keyboardWillChange:(NSNotification *)note
{
// 获得键盘的frame
CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
// 修改底部约束
self.bottomSpace.constant = self.view.frame.size.height - frame.origin.y;
// 执行动画
CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
[UIView animateWithDuration:duration animations:^{
[self.view layoutIfNeeded];
}];
}
-(void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
在实际开发中会遇到更多其他关于键盘处理的问题 在这里跟大家推荐一款好用的框架 IQKeyBoardManager