美文网首页
iOS-键盘遮挡输入框问题

iOS-键盘遮挡输入框问题

作者: fly大梦想家 | 来源:发表于2018-10-30 16:59 被阅读14次

原理:开始编辑时添加UIKeyboardWillShowNotification通知,通知中的信息可以获取到键盘的高度,根据高度来设置scrollView的contenOffset

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    //增加监听,当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    _backgroundView.contentOffset = CGPointMake(0,0 );
    [textField resignFirstResponder];    
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    return YES;
}
//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    for (UIView *subview in _backgroundView.subviews) {
      // 只对最下面的textField进行高度处理
        if ([subview isKindOfClass:[GOVTextField class]] && subview.tag == 102 ) {
            GOVTextField *isEditingTextField = (GOVTextField *)subview;
            if (isEditingTextField.isEditing) {
                _backgroundView.contentOffset = CGPointMake(0, height - (LAYOUT_SCREENSIZE_P.height- 65 - (_submitButton.frame.origin.y + _submitButton.frame.size.height)));
                return;
            }
        }else{
            _backgroundView.contentOffset = CGPointMake(0, 0);
        }
    }   
}
键盘遮挡处理.gif

升级xcode10后所有的东西都卡,电脑卡,模拟器更卡

相关文章

网友评论

      本文标题:iOS-键盘遮挡输入框问题

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