您的位置:首页 > 其它

通过NSNotification来监听键盘弹出和弹回

2015-11-01 22:55 211 查看
在通知中心建立一个广播来监听键盘的弹出和弹回,在监听事件中加入触发事件的一些操作。

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardwillhide:) name:UIKeyboardWillHideNotification object:nil];


监听键盘的一些通知:

// 键盘的frame发生改变时发出的通知(位置和尺寸)
//    UIKeyboardWillChangeFrameNotification
//    UIKeyboardDidChangeFrameNotification
// 键盘显示时发出的通知
//    UIKeyboardWillShowNotification
//    UIKeyboardDidShowNotification
// 键盘隐藏时发出的通知
//    UIKeyboardWillHideNotification
//    UIKeyboardDidHideNotification


在这里我需要实现的效果(如下图)是在在键盘弹出时,使下方的toolbar向上移动到相应位置,因此需要知道键盘的高度和弹出动画的时间,通过广播监听来得到键盘的frame和弹出动画时间:

NSString *duration = userInfo[UIKeyboardAnimationDurationUserInfoKey];
CGRect keyboardFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];


再通过动画效果,改变tableview和toolbar的frame,使得键盘在弹出时不会被遮挡:

[UIView animateWithDuration:[duration doubleValue] delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
_tableview.frame = CGRectMake(0, 64 , SIZE.width, SIZE.height - 64 - keyboardFrame.size.height - 50);
footView.frame = CGRectMake(0, SIZE.height - keyboardFrame.size.height - 50, SIZE.width, 50);
} completion:^(BOOL finished) {
NSIndexPath *path = [NSIndexPath indexPathForRow:_dataArray.count - 1 inSection:0];
[_tableview scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}];


效果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: