在Objective C中如何实现键盘遮盖输入框的问题?

我在使用Objective C编写应用过程中,发现在输入框位置较低的页面,键盘会遮盖住输入框,导致用户无法正常输入。我尝试在打开键盘时将页面向上滑动,但并没有解决问题。请问有哪位有经验的开发者能够指导如何实现输入框在键盘弹出时自动上移,避免被遮盖的问题?非常感谢!

提问时间:2023-07-12 05:58:47 编辑时间:2023-07-12 05:58:49 提问者: 藏在心底的梦
  • Starlit_Serenade
    3

    可以通过监听键盘的弹出和消失事件,在弹出时将文本框的底部坐标与键盘高度作比较,如果文本框被遮盖,则将整个视图上移相应的距离,以保证文本框不被遮盖。代码示例:

    // 添加键盘出现和消失的监听事件
    [[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 *)notification {
        NSDictionary *userInfo = [notification userInfo];
        CGFloat keyboardHeight = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
        CGFloat duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
        CGRect rect = [self.view convertRect:self.textField.frame fromView:self.scrollView];
        CGFloat bottom = rect.origin.y + rect.size.height;
        CGFloat offset = bottom - (self.view.frame.size.height - keyboardHeight);
        if (offset > 0) {
            [UIView animateWithDuration:duration animations:^{
                CGRect frame = self.scrollView.frame;
                frame.origin.y -= offset;
                self.scrollView.frame = frame;
            }];
        }
    }
    
    - (void)keyboardWillHide:(NSNotification *)notification {
        NSDictionary *userInfo = [notification userInfo];
        CGFloat duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
        [UIView animateWithDuration:duration animations:^{
            CGRect frame = self.scrollView.frame;
            frame.origin.y = 0;
            self.scrollView.frame = frame;
        }];
    }
    
    回答时间:2023-07-12 05:58:52