问题
How can I scroll to last row in tableview from current positon, because I have tried this solution:
self.tableView.scrollToRow(at: lastIndex.last!, at: .bottom , animated: false)
let numberOfSections = self.tableView.numberOfSections
let numberOfRows = self.tableView.numberOfRows(inSection: numberOfSections-1)
if numberOfRows > 0 {
let indexPath = IndexPath(row: numberOfRows-1, section: (numberOfSections-1))
self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: animated)
}
and it doesn't scroll from the current position but from the most top position. Even though my current position is the last row
回答1:
Do
func scrollToLastRow() {
let indexPath = NSIndexPath(forRow: objects.count - 1, inSection: 0)
self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Bottom, animated: true)
}
Scrolling means, thats from current position. So this code should work.
Otherwise you can specify the frame to scroll using scrollRectToVisible
tableView.scrollRectToVisible(tableView.rectForRowAtIndexPath(indexPath),animated: true)
回答2:
Try this code,
yourTableView.scrollRectToVisible(CGRect.init(x: 0, y: yourTableView.contentSize.height - yourTableView.frame.size.height, width: yourTableView.frame.size.width, height: yourTableView.frame.size.height), animated: true)
回答3:
You have to provide some more info that when you want to scroll your tableview to last index,Because this code works perfectly
let indexPath = IndexPath.init(row: lastRow, section: 0)
customTableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
Updated
Finally here is working code for me
@IBAction func sendBtnPressed(_ sender: UIButton) {
self.listMessages.append(messageTextView.text)
let lastIndexPath = IndexPath.init(row: self.listMessages.count-1, section: 0)
self.tableView.insertRows(at: [lastIndexPath], with: .none)
self.tableView.scrollToRow(at: lastIndexPath, at: .bottom, animated: true)
messageTextView.text = "";
}
回答4:
For swift 4
func scrollToLastRow() {
if CommentNameArray.count != 0 {
let indexPath = NSIndexPath(row: CommentNameArray.count - 1, section: 0)
self.CommentTableView.scrollToRow(at: indexPath as IndexPath, at: .bottom, animated: true)
}
}
来源:https://stackoverflow.com/questions/45205592/uitableview-scroll-to-bottom-from-current-position