1.监听键盘通知
- (void)viewDidLoad
{
[super viewDidLoad];
// 监听键盘的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
当键盘改变了 frame( 位置和尺寸 ) 的时候调用
- (void)keyboardWillChangeFrame:(NSNotification *)note
{
// 设置窗口的颜色
self.view.window.backgroundColor = self.tableView.backgroundColor;
// 0.取出键盘动画的时间
CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
// 1.取得键盘最后的frame
CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
// 2.计算控制器的view需要平移的距离
CGFloat transformY = keyboardFrame.origin.y - self.view.frame.size.height;
// 3.执行动画
[UIView animateWithDuration:duration animations:^{
self.view.transform = CGAffineTransformMakeTranslation(0, transformY);
}];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
// 退出键盘
[self.view endEditing:YES];
}
3.注销监听器
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}