首先初始化的时候添加通知
//键盘弹出
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
//键盘回收
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
UI上移和恢复的实现方法
- (void)KeyboardWillShow:(NSNotification *)note
{
CGRect keyboardBounds;
[[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
// 获取键盘弹出动画时间
NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
// 将rect由rect所在视图转换到目标视图view中,返回在目标视图view中的rect 即获得键盘在backView的frame
keyboardBounds = [self convertRect:keyboardBounds toView:nil];
//要设置要上移的视图 我的是backView
CGRect supViewFrame = self.backView.frame;
//设置动画
[UIView beginAnimations:nil context:NULL];
//设置动画是否将从当前视图状态进行动画处理。
[UIView setAnimationBeginsFromCurrentState:YES];
//设置动画时间
[UIView setAnimationDuration:[duration doubleValue]];
//动画节奏
[UIView setAnimationCurve:[curve intValue]];
//重新设置backView的位置
supViewFrame.origin.y = SCREENH_HEIGHT - keyboardBounds.size.height - supViewFrame.size.height + 50;
self.backView.frame = supViewFrame;
[UIView commitAnimations];
}
- (void)KeyboardWillHide:(NSNotification *)note{
NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
// animations settings
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:[duration doubleValue]];
[UIView setAnimationCurve:[curve intValue]];
//
CGRect supViewFrame = self.backView.frame;
supViewFrame.origin.y = SCREENH_HEIGHT - supViewFrame.size.height;
self.backView.frame = supViewFrame;
[UIView commitAnimations];
}
移除通知
-(void)dealloc
{
//移除该控制器下的所有通知
[[NSNotificationCenter defaultCenter] removeObserver:self];
//移除名称为UIKeyboardWillShowNotification的那个通
//[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}