iOS 多个输入框弹出键盘处理

发布于:2025-02-11 ⋅ 阅读:(98) ⋅ 点赞:(0)

开发中遇到这样一个场景,有多个输入框
而不同的输入框,需要页面向上偏移的距离不一样
这个时候,需要我们在获取到键盘弹出通知的时候,需要
知道我们开始进行编辑的是哪一个输入框,这个时候
需要我们知道一个技术点,就是
**textField的开始编辑的响应方法textFieldDidBeginEditing是比键盘弹出的通知要早的,**根据这个特性,我们就可以在开始编辑的时候,记录一个是哪一个输入框开始了,根据他的位置,设置相应的偏移量

#代码

设置代理

    _nameTextField.delegate = self;

实现代理方法

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if ([self.delegate respondsToSelector:@selector(didBeginEditing:)]) {
        [self.delegate didBeginEditingInView:self];
    }
}

实现方法

- (void)didBeginEditingInView:(AuthenticationVAccountView *)authenticationAccountView {
    self.editAccountView = authenticationAccountView;
    NSLog(@" didBeginEditingInAuthenticationAccountView");
}

键盘通知

- (void)keyboardWillShow:(NSNotification *)noti
{
    AuthenticationVAccountView *userInforView = self.editAccountView;
    
    CGRect userInfoViewframe = [self.scrollView convertRect:userInforView.frame toView:DTContextGet().window];
    CGFloat bottomSpace = UIGetScreenHeight()  - CGRectGetMaxY(userInfoViewframe);
    //设置一个buffer
    bottomSpace -= 40;
    CGRect keyboardRect = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat boardHeight = keyboardRect.size.height;
    if ((boardHeight - bottomSpace) < 0) {
        return;
    }
    CGFloat duration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    Weakify(self);
    [UIView animateWithDuration:duration animations:^{
        Strongify(self);
        self.scrollView.y -= (boardHeight - bottomSpace);
        self.backgroundView.y -= (boardHeight - bottomSpace);
    }];
}

网站公告

今日签到

点亮在社区的每一天
去签到