[英]swift3 scrollToRow even when there are empty cells
I'm looking for a way to scroll to the selected cell in UITableView even if there a empty cells at bottom. 我正在寻找一种滚动到UITableView中选定单元格的方法,即使底部有一个空单元格也是如此。 My problem is that the scroll event does not scroll when there are no cells at the bottom of a table view. 我的问题是,当表格视图底部没有单元格时,scroll事件不会滚动。
As a workaround I ended up creating empty cells at the bottom and deleting those cells but I don't think that this is a good solution. 作为一种解决方法,我最终在底部创建了空单元格并删除了这些单元格,但我认为这不是一个好的解决方案。 So how is the way of doing this? 那么如何做到这一点呢?
My code looks like this: 我的代码如下所示:
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()
}
}
You can do this more elegantly using the fact that UITableView inherits from UIScrollView. 您可以使用UITableView继承自UIScrollView的事实来更优雅地执行此操作。 This allows you to use a combination of setting the content inset for the tableView and then changing the content offset. 这使您可以组合使用以下方法:设置tableView的内容插入,然后更改内容偏移量。
Use the contentInset property to add a margin within the table view below your cells: 使用contentInset属性在单元格下方的表格视图中添加边距:
tableView.contentInset = UIEdgeInsetMake(top: 0, left: 0, bottom: A LARGE NUMBER, right: 0)
Then use contentOffset to set where you want the initial position of the content to be in the scrollview: 然后使用contentOffset设置内容的初始位置在滚动视图中的位置:
tableView.contentOffset = CGPoint(x: 0, y: SOME OTHER LARGE NUMBER TO POSITION CENTRALLY IN THE MARGIN)
You can get further information at: https://developer.apple.com/reference/uikit/uiscrollview 您可以在以下位置获取更多信息: https : //developer.apple.com/reference/uikit/uiscrollview
Hope that helps. 希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.