您的位置:首页 > 移动开发 > IOS开发

ios 利用通知处理键盘的显示与隐藏

2014-09-15 20:08 411 查看
1.监听键盘通知

<
4000
span style="font-size:18px;">

- (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);
    }];
}

 2.当开始拖拽表格的时候调用(隐藏键盘)
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    // 退出键盘
    [self.view
endEditing:YES];
}
3.注销监听器

- (void)dealloc
{
    [[NSNotificationCenter
defaultCenter] removeObserver:self];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  键盘处理