首先需要监听键盘通知,这里我们监听UIKeyboardWillChangeFrameNotification,只要键盘位置改变了(不管是弹出还是隐藏),系统都会发出该通知.
其次调整View(被键盘弹出隐藏的控件)的高度.(这里我们就需要知道通知的内容,因为通知中包含了键盘弹出和隐藏的所有信息).
//—-打印出来通知的userInfo信息——
/*UIKeyboardAnimationCurveUserInfoKey = 7;
UIKeyboardAnimationDurationUserInfoKey = “0.25”;
UIKeyboardBou…
1.首先注册系统通知
//监听键盘通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrameNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];
2.键盘将要改变时的相应处理
-(void)keyboardWillChangeFrameNotification:(NSNotification *)note{
//取出键盘动画的时间(根据userInfo的key----UIKeyboardAnimationDurationUserInfoKey)
CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
//取得键盘最后的frame(根据userInfo的key----UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 227}, {320, 253}}";)
CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
//计算控制器的view需要平移的距离
CGFloat transformY = keyboardFrame.origin.y - self.view.frame.size.height;
//执行动画
[UIView animateWithDuration:duration animations:^{
//平移
self.view.transform = CGAffineTransformMakeTranslation(0, transformY);
}];
}
3.这样其实还没完(存在内存隐患)还需要重写dealloc方法
-( void )dealloc{
// 使用通知中心后必须重写 dealloc 方法 , 进行释放 (ARC)( 非 ARC 还需要写上[super dealloc];)
//removeObserver和 addObserver相对应.
[[ NSNotificationCenter defaultCenter ] removeObserver : self ];
}