1、键盘的自带通知 (见名知意)
UIKeyboardWillShowNotification 键盘将要显示
UIKeyboardDidShowNotification 键盘显示完毕
UIKeyboardWillHideNotification 键盘将要隐藏
UIKeyboardDidHideNotification 键盘完成隐藏
UIKeyboardWillChangeFrameNotification 键盘frame将要改变
UIKeyboardDidChangeFrameNotification 键盘frame完成改变
(frame改变不论是显示还是隐藏都会发送该通知)
注册:[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
其他类似。
2、细节ios5之前,iphone上的键盘的高度是固定为216.0px高的,中文汉字的选择框是悬浮的,所以不少应用都将此高度来标注键盘的高度。但显然这是不合理的。
在开发中其实这些通知并不能按照你所想的那样发生,要注意以下几点:
1. 当在英文和中文输入法之间切换时,iPhone中并不会产生UIKeyboardWillChangeFrameNotification和UIKeyboardDidChangeFrameNotification通知,而iPad中会产生。
2. ChangeFrame Notification会发生在Show或Hide Notification之前。
3. 在iPad中分割键盘会有Hide Notification,合并键盘时才有Show Notification。分割时键盘竟然是隐藏的。
3、使用
#pragma mark - 注册通知
- (void)addNotification
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardDidHideNotification object:nil];
}
#pragma mark - UIKeyboardNotification
/* 键盘显示*/
- (void)keyboardShow:(NSNotification *)notification
{
NSDictionary* info = [notification userInfo];
float duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
CGFloat keyboardHeight = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
[UIView animateWithDuration:duration animations:^{
self.rootView.y = 0;
//因为在textField代理方法中写了alert,故键盘显示后又会隐藏,alert点击关闭后键盘会再次弹出,此时就会上移都一次,并且当键盘发生改变的时候也会发送show的通知,会多次调用
self.rootView.frame.origin.y -= keyboardHeight;//重新设置上移高度
}];
}
/* 键盘隐藏*/
- (void)keyboardHide:(NSNotification *)notification
{
NSDictionary* info = [notification userInfo];
float duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
CGFloat keyboardHeight = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
[UIView animateWithDuration:duration animations:^{
self.rootView.frame.origin.y += keyboardHeight;
}];
}
/* 移除通知*/
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
下面说一下text输入框的两个代理方法和键盘通知之间的先后顺序
UIKeyboardWillShowNotification (did)
- (void)textFieldDidBeginEditing
- (void)textFieldDidEndEditing
UIKeyboardWillHideNotification (did)
从上至下依次执行。