I've a UITableView
and I'm trying to load 36 rows into it and then scroll all the way down the last cell.
I've tried this:
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)
}
}
}
But it only scrolls down halfway.
To scroll to the bottom of the table view items, use ScrollToRow. Three parameters are required for this: NSIndexPath: Specify which row item to scroll to.
UITableView is a subclass of UIScrollView that allows users to scroll the table vertically (the closely-related UICollectionView class allows for horizontal scrolling and complex two-dimensional layouts).
To scroll to the top of our tableview we need to create a new IndexPath . This index path has two arguments, row and section . All we want to do is scroll to the top of the table view, therefore we pass 0 for the row argument and 0 for the section argument. UITableView has the scrollToRow method built in.
A view that presents data using rows in a single column. iOS 2.0+ iPadOS 2.0+ Mac Catalyst 13.1+ tvOS 9.0+
If your requirement is to scroll to the last cell
of tableView
you can use setContentOffset
like this so that you can scroll to the last cell of tableView
.
Put this in the reloadData() function:
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)
})
}
Add this to your UITableViewDelegate :
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
let lastRowIndex = tableView.numberOfRowsInSection(0)
if indexPath.row == lastRowIndex - 1 {
tableView.scrollToBottom(true)
}
}
Add this to the bottom of your .swift file:
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)
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With