Rut*_*ans 5 uitableview ios swift
我有一个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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
但它只会向下滚动一半.
Nir*_*v D 11
如果您的要求是滚动到最后一个cell,tableView可以setContentOffset像这样使用,以便您可以滚动到最后一个单元格tableView.
let scrollPoint = CGPoint(x: 0, y: self.tableView.contentSize.height - self.tableView.frame.size.height)
self.tableView.setContentOffset(scrollPoint, animated: true)
Run Code Online (Sandbox Code Playgroud)
这是答案的组合.我最终这样做了:
把它放在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)
})
}
Run Code Online (Sandbox Code Playgroud)
将此添加到我的UITableViewDelegate:
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
let lastRowIndex = tableView.numberOfRowsInSection(0)
if indexPath.row == lastRowIndex - 1 {
tableView.scrollToBottom(true)
}
}
Run Code Online (Sandbox Code Playgroud)
将其添加到我的.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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8613 次 |
| 最近记录: |