【发布时间】:2021-11-01 23:08:57
【问题描述】:
UITableViewController虽然可以在键盘显示时自动调整表格视图,但不够灵活。我尝试使用UIViewController 和UITableView 来构建我的用户界面。
表格视图中有许多单元格。在所有单元格中,有一个单元格为UITextField。当我点击该文本字段时,键盘显示并且即使单元格被键盘覆盖,表格视图也不会执行任何操作。没关系,因为这是预期的结果。
奇怪的事情来了。如果我给表格视图一个大的contentInset.bottom,例如contentInset.bottom = 600,当键盘显示时表格视图会自动滚动。
我尽量避免使用tableView.contentInsetAdjustmentBehavior = .never。
以下代码显示了这种奇怪的行为。可在iOS 14.5、iPhone 12 mini Simulator 上重现。
class TestViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let tableView = UITableView()
override func loadView() {
view = tableView
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
tableView.delegate = self
tableView.dataSource = self
tableView.contentInset.bottom = 600
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
print("scrolling contentOffset-Y: \(scrollView.contentOffset.y)")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Ugly code, only for showing the problem.
let cell = UITableViewCell()
if indexPath.row == 9 {
let textField = UITextField()
cell.contentView.addSubview(textField)
textField.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
textField.leadingAnchor.constraint(equalTo: cell.contentView.layoutMarginsGuide.leadingAnchor),
textField.trailingAnchor.constraint(equalTo: cell.contentView.layoutMarginsGuide.trailingAnchor),
textField.topAnchor.constraint(equalTo: cell.contentView.layoutMarginsGuide.topAnchor),
textField.bottomAnchor.constraint(equalTo: cell.contentView.layoutMarginsGuide.bottomAnchor),
])
} else {
cell.textLabel?.text = "\(indexPath)"
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
}
【问题讨论】:
标签: ios uitableview uiscrollview uikit