一直向下滚动到UITableView的底部
我有一个UITableView
,我正在尝试加载36行,然后一直向下滚动到最后一个单元格。
我试过这个:
func reloadData(){ chatroomTableView.reloadData() chatroomTableView.scrollToBottom(true) } extension UITableView { func scrollToBottom(animated: Bool = true) { let sections = self.numberOfSections let rows = self.numberOfRowsInSection(sections - 1) if (rows > 0){ self.scrollToRowAtIndexPath(NSIndexPath(forRow: rows - 1, inSection: sections - 1), atScrollPosition: .Bottom, animated: true) } } }
但它只会向下滚动一半。
如果你的要求是滚动到tableView
的最后一个cell
,你可以像这样使用setContentOffset
这样你就可以滚动到tableView
的最后一个单元格。
let scrollPoint = CGPoint(x: 0, y: self.tableView.contentSize.height - self.tableView.frame.size.height) self.tableView.setContentOffset(scrollPoint, animated: true)
这是答案的组合。 我最终这样做了:
把它放在reloadData()函数中:
func reloadData(){ chatroomTableView.reloadData() dispatch_async(dispatch_get_main_queue(), { () -> Void in let scrollPoint = CGPoint(x: 0, y: self.chatroomTableView.contentSize.height - self.chatroomTableView.frame.size.height) self.chatroomTableView.setContentOffset(scrollPoint, animated: true) }) }
将此添加到我的UITableViewDelegate:
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { let lastRowIndex = tableView.numberOfRowsInSection(0) if indexPath.row == lastRowIndex - 1 { tableView.scrollToBottom(true) } }
将其添加到我的.swift文件的底部:
extension UITableView { func scrollToBottom(animated: Bool = true) { let sections = self.numberOfSections let rows = self.numberOfRowsInSection(sections - 1) if (rows > 0){ self.scrollToRowAtIndexPath(NSIndexPath(forRow: rows - 1, inSection: sections - 1), atScrollPosition: .Bottom, animated: true) } } }