0、优势说明
1、多个观察者
// 添加系统通知观察者(检测键盘的显示与隐藏)
// 检测键盘的弹起
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
// 检测键盘的隐藏
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];
// 键盘弹起事件处理
- (void)keyboardShow:(NSNotification *)notification {
// 取出键盘最终的高度
CGFloat keyboardHeight = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
// 取出键盘弹出需要花费的时间
double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
// 设置当前视图的 frame
CGRect frame = self.view.frame;
frame.origin.y = -keyboardHeight;
[UIView animateWithDuration:duration animations:^{
self.view.frame = frame;
}];
}
// 键盘隐藏事件处理
- (void)keyboardHide:(NSNotification *)notification {
// 取出键盘弹出需要花费的时间
double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
// 设置当前视图的 frame
CGRect frame = self.view.frame;
frame.origin.y = 0;
[UIView animateWithDuration:duration animations:^{
self.view.frame = frame;
}];
}
2、单一观察者
// 添加系统通知观察者(检测键盘的 frame 改变)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification
object:nil];
// 键盘弹起隐藏事件处理
- (void)keyboardWillChangeFrame:(NSNotification *)notification {
// 取出键盘最终的 frame
CGRect rect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
// 取出键盘弹出需要花费的时间
double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
// 设置当前视图的 frame
CGRect frame = self.view.frame;
frame.origin.y = -([UIScreen mainScreen].bounds.size.height - rect.origin.y);
[UIView animateWithDuration:duration animations:^{
self.view.frame = frame;
}];
}
3、视图上升或下降处理
CGRect frame = self.view.frame;
frame.origin.y = -keyboardHeight;
[UIView animateWithDuration:duration animations:^{
self.view.frame = frame;
}];
self.bottomSpacing.constant = rect.size.height;
[UIView animateWithDuration:duration animations:^{
[self.view layoutIfNeeded];
}];
[UIView animateWithDuration:duration animations:^{
CGFloat ty = [UIScreen mainScreen].bounds.size.height - rect.origin.y;
self.view.transform = CGAffineTransformMakeTranslation(0, -ty);
}];