键盘弹出/隐藏,界面滚动

假设需滚动界面为控制器的view,需进行以下操作

1.添加键盘frame变化监听

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

2.实现KeyboardWillChangeFrame方法,更改view左上角(原点)y值

- (void)KeyboardWillChangeFrame:(NSNotification *)notification
{
    //背景色调整,避免出现黑色背景
    self.view.window.backgroundColor = self.view.backgroundColor;
    
    //获取键盘frame
    CGRect keyboardFrame=[notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    //键盘移动时间
    CGFloat keyDuration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    //键盘移动距离
    CGFloat originY=CGRectGetHeight(self.view.frame)-CGRectGetMinY(keyboardFrame);
    
    if (CGRectGetMidY(keyboardFrame)>=CGRectGetHeight(self.view.frame)) {//判断键盘是否低于底边
        //键盘隐藏,原点y在0位置
        originY = originY;
        
    } else {
        //键盘弹出,原点y在在负移动间隔
        originY = -originY ;
    }
    
    //执行动画
    [UIView animateWithDuration:keyDuration animations:^{
           //判断某个控件触发键盘弹出
         //if([self.queryAge isFirstResponder]||[self.queryName isFirstResponder]){
            //原点移动到(0,originY)位置
           self.view.transform = CGAffineTransformMakeTranslation(0,originY);
         // } 
    }];
    
}

 

3.释放监听

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}
posted @ 2016-03-04 16:29  -Eazy-  阅读(293)  评论(0编辑  收藏  举报