我正在寻找一种方法来滚动到 UITableView 中的选定单元格,即使底部有空单元格也是如此。我的问题是,当表格 View 底部没有单元格时,滚动事件不会滚动。
作为解决方法,我最终在底部创建了空单元格并删除了这些单元格,但我认为这不是一个好的解决方案。那么如何做到这一点呢?
我的代码是这样的:
func scrollToSelectedCell(indexPath: IndexPath) {
self.tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.top, animated: true)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
if (cell as? DropDownCell) != nil {
self.performSegue(withIdentifier: "showDropDownSelector", sender: cell)
} else if (cell as? PickerCell) != nil {
self.performSegue(withIdentifier: "showPickerSelector", sender: cell)
} else if let tmp_cell = cell as? TextFieldCell {
scrollToSelectedCell(indexPath: indexPath)
tmp_cell.textField.becomeFirstResponder()
}
}
最佳答案
使用 UITableView 继承自 UIScrollView 的事实,您可以更优雅地完成此操作。这允许您结合使用设置 tableView 的内容插入,然后更改内容偏移量。
使用 contentInset 属性在单元格下方的表格 View 中添加边距:
tableView.contentInset = UIEdgeInsetMake(top: 0, left: 0, bottom: A LARGE NUMBER, right: 0)
然后使用 contentOffset 设置您希望内容在 ScrollView 中的初始位置:
tableView.contentOffset = CGPoint(x: 0, y: SOME OTHER LARGE NUMBER TO POSITION CENTRALLY IN THE MARGIN)
您可以在以下网址获得更多信息:https://developer.apple.com/reference/uikit/uiscrollview
希望对您有所帮助。
关于ios - swift3 scrollToRow 即使有空单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39874279/