【问题标题】:Textfields under keyboard键盘下的文本字段
【发布时间】:2015-08-29 17:00:26
【问题描述】:

在我的应用中,表单很少。有时键盘会隐藏字段,因此用户无法看到他输入的内容。对于这种情况,我找到了向上移动视图或滚动视图的方法,以便文本字段保持在键盘上方。 问题是在 iPhone 5 上我需要将最后 3 个文本字段的视图向上移动,但对于 iPhone 6 - 仅用于最后一个文本字段。

当然,我可以定义字段和设备屏幕高度值的所有情况。 但我想找到更优雅的解决方案来检测 texfield 是否在当前设备的键盘下,是否有必要移动视图?

【问题讨论】:

  • 获取键盘高度,看看屏幕底部到文本框底部是否大于那个距离
  • 考虑使用每行包含一个字段的 UITableView。当焦点移动到 UITextField 时,滚动到相应的 UITableView 行。

标签: ios swift


【解决方案1】:

使用TPKeyboardAvoidingScrollView。它易于使用

将 TPKeyboardAvoidingScrollView.m 和 TPKeyboardAvoidingScrollView.h 源文件拖放到您的项目中,将 UIScrollView 弹出到视图控制器的 xib 中,将滚动视图的类设置为 TPKeyboardAvoidingScrollView,然后将所有控件放在该滚动视图中。您也可以通过编程方式创建它,而无需使用 xib - 只需使用 TPKeyboardAvoidingScrollView 作为您的顶级视图。

【讨论】:

  • 谢谢。我绝对需要尝试
【解决方案2】:

Apple here 提供了很好的帮助指南

您需要收听键盘通知,例如

// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
            selector:@selector(keyboardWasShown:)
            name:UIKeyboardDidShowNotification object:nil];

   [[NSNotificationCenter defaultCenter] addObserver:self
             selector:@selector(keyboardWillBeHidden:)
             name:UIKeyboardWillHideNotification object:nil];

}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;

    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your app might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
        [self.scrollView scrollRectToVisible:activeField.frame animated:YES];
    }
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;
}

【讨论】:

  • 只有在有滚动视图时才适用,在有视图时不适用
  • 原理还是一样的。您会收到通知,获取键盘高度,查看选定的 UITextField 并查看其容器视图是否需要向上移动。
【解决方案3】:

您可以使用其委托方法- (void)textFieldDidBeginEditing:(UITextField *)textField 检测哪个UITextField 是“活动”的。

使用textField.frame 计算您需要为scrollView.contentOffset 设置的偏移量。 在- textFieldDidBeginEditing: 方法中,您可以重置contentOffset = CGPointZero

【讨论】:

    猜你喜欢
    • 2020-09-17
    • 1970-01-01
    • 2016-12-28
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 2014-03-18
    • 2011-01-19
    • 1970-01-01
    相关资源
    最近更新 更多