有时当键盘弹出和退出时,有些控件view需要同步键盘的动作节奏,可以使用下面的方法。
(1),添加键盘通知
// 监听键盘的通知(一旦键盘发生改变,系统会主动发布一些通知,我们只需要监听就可以)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
(2),设置self.view和键盘同步
- (void)keyBoardWillChangeFrame:(NSNotification *)note
{
// // 键盘弹出的时候 整个self.view都往上移动
// self.view.transform = CGAffineTransformMakeTranslation(0, -216);
//
// // 键盘隐藏的时候,改变sel.view回到原位
// self.view.transform = CGAffineTransformMakeTranslation(0, 0);
// 取得键盘改变frame以后的frame(取得键盘最后的frame)
CGRect transYFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
// 计算self.view需要移动距离(当键盘弹出的时候,距离是-216。当键盘隐藏的时候,距离是0)
CGFloat transfomY = transYFrame.origin.y - self.view.frame.size.height;
// 取得键盘动画的时间
CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
// 执行动画
[UIView animateWithDuration:duration animations:^{
self.view.transform = CGAffineTransformMakeTranslation(0, transfomY);
}];
// 设置window颜色
self.view.window.backgroundColor = self.tableView.backgroundColor;
// NSLog(@"note%@", note.userInfo);
}
// 键盘弹出的时候,看到黑色,1.由于动画的不同步 2.self.view.window
// 当表格开始拖拽的时候,就退出键盘
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
// 退出键盘
[self.view endEditing:YES];
}