美文网首页iOS工作环境搭建iOS
iOS键盘监听处理遮挡控件问题(整理)

iOS键盘监听处理遮挡控件问题(整理)

作者: CCSHCoder | 来源:发表于2016-07-15 14:02 被阅读222次
    #pragma mark - 键盘处理
    #pragma mark 监听系统发出的键盘通知
    - (void)addKeyboardNote
    {
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        
        // 1.显示键盘
        [center addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        
        // 2.隐藏键盘
        [center addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    }
    
    • 显示方法
    #pragma mark 显示一个新的键盘就会调用
    - (void)keyboardWillShow:(NSNotification *)note
    {
        // 1.取得当前聚焦文本框最下面的Y值
        CGFloat loginBtnMaxY = CGRectGetMaxY(loginBtn.frame);
        // 2.取出键盘的高度
        CGFloat keyboardH = [note.userInfo [UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
        // 3.控制器view的高度 - 键盘的高度
        CGFloat keyboardY = self.view.frame.size.height - keyboardH;
        // 4.比较登录按钮最大Y 跟 键盘Y
        CGFloat duration = [note.userInfo [UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
        if (duration <= 0.0) {
            duration = 0.25;
        }
        
        [UIView animateWithDuration:duration animations:^{
            if (loginBtnMaxY > keyboardY) { // 键盘挡住了登录按钮
                self.view.transform = CGAffineTransformMakeTranslation(0, keyboardY - loginBtnMaxY - 8);
            } else { // 没有挡住登录按钮
                self.view.transform = CGAffineTransformIdentity;
            }
        }];
    }
    
    • 隐藏方法
    #pragma mark 隐藏键盘就会调用
    - (void)keyboardWillHide:(NSNotification *)note
    {
        CGFloat duration = [note.userInfo [UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        [UIView animateWithDuration:duration animations:^{
            self.view.transform = CGAffineTransformIdentity;
        }];
    }
    
    • 销毁处理
    - (void)dealloc
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    

    相关文章

      网友评论

        本文标题:iOS键盘监听处理遮挡控件问题(整理)

        本文链接:https://www.haomeiwen.com/subject/tsyyjttx.html