美文网首页
iOS 处理UITextField被键盘遮挡的问题

iOS 处理UITextField被键盘遮挡的问题

作者: huGh11 | 来源:发表于2019-08-02 11:40 被阅读0次

    都在注释里

    //增加监听,当键盘出现或改变时收出消息
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        
        //增加监听,当键退出时收出消息
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    - (void)keyboardWillShow:(NSNotification *)aNotification{
        
        NSDictionary *userInfo = [aNotification userInfo];
        NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
        CGRect keyboardRect = [aValue CGRectValue];
        int height = keyboardRect.size.height;
        
        // 设置动画的名字
        [UIView beginAnimations:@"Animation" context:nil];
        // 设置动画的间隔时间
        [UIView setAnimationDuration:0.20];
        // 使用当前正在运行的状态开始下一段动画
        [UIView setAnimationBeginsFromCurrentState: YES];
        // 获取到textfiled 距底部距离
        int textToTop = self.view.frame.size.height - self.numberTextFiled.frame.origin.y - self.numberTextFiled.frame.size.height;
        
        if (textToTop > height) {
            // 如果键盘高度小于textfiled距底部的距离 则不需要任何操作
        }else{
            // 当textToTop 小于 height 时
            // 获取到键盘高度和控件底部距离的差值
            int scrolldistance = height - textToTop;
            // 移动视图y 差值距离
            self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y - scrolldistance, self.view.frame.size.width, self.view.frame.size.height);
        }
        //设置动画结束
        
        [UIView commitAnimations];
        
        
    }
    
    //当键退出时调用
    - (void)keyboardWillHide:(NSNotification *)aNotification{
        // 设置动画的名字
        [UIView beginAnimations:@"Animation" context:nil];
        // 设置动画的间隔时间
        [UIView setAnimationDuration:0.20];
        // 使用当前正在运行的状态开始下一段动画
        [UIView setAnimationBeginsFromCurrentState: YES];
        // 设置视图移动的位移至原来的y值
        self.view.frame = CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width, self.view.frame.size.height);
        //设置动画结束
        [UIView commitAnimations];
        
    }
    

    相关文章

      网友评论

          本文标题:iOS 处理UITextField被键盘遮挡的问题

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