原理:利用通知来实现对键盘状态的监听
直接上代码
1.注册通知
/*
键盘即将弹出
UIKeyboardWillShowNotification
键盘已经弹出
UIKeyboardDidShowNotification
键盘即将隐藏
UIKeyboardWillHideNotification
键盘已经隐藏
UIKeyboardDidHideNotification
键盘frame变化
UIKeyboardWillChangeFrameNotification
*/
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldShouldChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
2.实现通知方法
- (void)textFieldShouldChangeFrame:(NSNotification *)notification{
//通知中的字典信息
NSDictionary *dict = notification.userInfo;
CGRect beginRect = [dict[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
CGRect endRect = [dict[UIKeyboardFrameEndUserInfoKey] CGRectValue];
/* 键盘弹出高度变化 */
CGFloat changeY = beginRect.origin.y - endRect.origin.y;
/* 键盘弹出动画时间 */
NSTimeInterval time = [dict[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
/* 利用动画改变键盘位置 */
[UIView animateWithDuration:time animations:^{
_textField.frame = CGRectMake(0, _textField.frame.origin.y - changeY, _textField.frame.size.width, _textField.frame.size.height);
}];
}
3.移除通知
- (void)dealloc{
/* 移除通知 */
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}