在iOS11中,当编辑文本字段时,tableViewCell不会自动向上滚动。这是因为iOS11引入了一个新的特性,即自动调整滚动视图的内边距。默认情况下,当键盘弹出时,iOS会自动调整滚动视图的内边距,以确保文本字段可见并避免被键盘遮挡。
要解决这个问题,可以通过以下步骤来实现tableViewCell的向上滚动:
以下是一个示例代码,演示如何实现tableViewCell的向上滚动:
// 监听键盘弹出和收起的通知
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
// 键盘弹出通知的回调方法
@objc func keyboardWillShow(_ notification: Notification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
// 计算需要滚动的距离
let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
tableView.contentInset = contentInsets
tableView.scrollIndicatorInsets = contentInsets
// 获取当前编辑的文本字段所在的indexPath
if let indexPath = getIndexPathForEditingTextField() {
// 滚动tableViewCell
tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
}
}
}
// 键盘收起通知的回调方法
@objc func keyboardWillHide(_ notification: Notification) {
// 恢复tableView的内边距
tableView.contentInset = .zero
tableView.scrollIndicatorInsets = .zero
}
// 获取当前编辑的文本字段所在的indexPath
func getIndexPathForEditingTextField() -> IndexPath? {
// 遍历tableView的所有可见的indexPath
for indexPath in tableView.indexPathsForVisibleRows ?? [] {
let cell = tableView.cellForRow(at: indexPath)
if let textField = cell?.viewWithTag(1) as? UITextField, textField.isEditing {
return indexPath
}
}
return nil
}
这样,当编辑文本字段时,tableViewCell会自动向上滚动,以确保文本字段可见。
领取专属 10元无门槛券
手把手带您无忧上云