table 视图仅滚动到文本字段底部边缘

table views only scrolls to textfields bottom edge

我的 table 视图的最底部单元格是一个带有文本字段的单元格。当用户点击它时,我想滚动它,使单元格位于键盘正上方。

当我用 animated false 调用 scrollRectToVisible(...) 时,一切都按预期工作,但是当 animated 设置为 true 时, table 滚动单元格到此为止,textField 的底部刚好在键盘上方 (见左图)。但是 bottonInsets 应该是正确的,因为我可以手动将单元格滚动到最后一位,并且单元格正确放置 (见右图)

我认为 table 视图在键盘上方滚动 textField 的底部边缘是 table 视图的默认行为,但恐怕我不知道为什么它似乎覆盖了当我想要动画时我自己滚动。

左图:
键盘正上方的 textFields 底部边缘(我保留了边框样式,这样您可以看得更清楚)。

右图: 我多么想要它。键盘上方单元格的底部边缘。

func repositionTextfieldCell(in tableView: UITableView) {
    guard let textFieldCell = tableView.bottommostCell() else { return }
    guard let keyboardRect = activeKeyboardRect else { return }

    // - Adjust insets

    var bottomInset = keyboardRect.size.height

    tableView.contentInset.bottom = bottomInset
    tableView.scrollIndicatorInsets.bottom = bottomInset

    // - Make cell visible

    let x = textFieldCell.frame.minX
    let y = textFieldCell.frame.maxY

    tableView.scrollRectToVisible(CGRect(origin: CGPoint(x: x, y: y),
                                         size: CGSize(width: 1, height: 1)), animated: true)
}

在 viewDidLoad() 中添加这个并为 tableview 底部创建一个 NSlayout 约束。

NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillShow),
name: NSNotification.Name.UIKeyboardWillShow,
object: nil
)

创建函数

@objc func keyboardWillShow(_ notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
    let keyboardRectangle = keyboardFrame.cgRectValue
    let keyboardHeight = keyboardRectangle.height
    tableBottomConstraint.constant = self.view.frame.height - keyboardHeight
}
}

重复此过程以在 keyboardWillHide() 方法中重置 tableBottomConstraint.constant = 0。

我可以解决这个问题。

该行为似乎取决于调用了 scrollRectToVisible(...)。当在 keyboardDidShow(...).

中调用 scrollRectToVisible(...) 时,我在问题中描述的行为就会发生

然而,当您在 keyboardWillShow(...) 中调用 scrollRectToVisible(...) 并将 animated 设置为 false 时,单元格/矩形被滑入的键盘向上推。我认为看起来太好了。