The following worked for my Swift 3.1 code using Xcode 8.3.2 targeting iOS 10.1 for iPhone only.
I had the same problem as the OP. My app included a messaging function. I wanted the last post to be visible when the message view was pushed onto the stack. My tableview cell heights are variable due to the content of the messages. None of the solutions worked to my satisfaction (the last tableview row was not visible or only partially visible). But, here is what worked for me:
- In the Interface Builder (IB) set the cell Row Height to a value greater than I expected my average row height to be in my case 50 (make sure to check the 'Custom' checkbox).
In the ViewController where the tableview is implemented inside the 'viewDidLoad' function set the tableview's 'rowHeight' property as follows:
myTableView.rowHeight = UITableViewAutomaticDimension
Also in the 'viewDidLoad' function set the tableview's 'estimatedRowHeight' to a value higher than you expect your average row height to be. In my case 140.
Finally and most importantly I wrote this bit of code:
extension UITableView {
func scrollToBottom() {
let rows = self.numberOfRows(inSection: 0)
let indexPath = IndexPath(row: rows - 1, section: 0)
self.scrollToRow(at: indexPath, at: .top, animated: true)
}
}
Notice the at: .top
— this is what solved my problem. Passing the .bottom
value for the UITableViewScrollPosition
parameter just didn't work. Even passing .middle
worked — but not .bottom
.
So, any time my dataset need to be updated or a new message arrives I call
func getTableViewData(){
// Get your data here any way you usually do..
// call to reload
myTableView.reloadData()
// call the scroll function
myTableView.scrollToBottom()
}
I tested the results of this 'method' by simply changing the at: .bottom
parameter to at: .top
. Every time I changed it to at: .top
the last table rows were fully visible and the table scrolled all the way to the bottom.