Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting correct ContentSize.height of TableView

I have UITableView inside of UIScrollView. After I fetched some data from server,I reloaded tableview and after that I get tableview content height and change the height of tableView to that content height and call layoutIfNeed() on scrollView.

But the problem is that the contentHeight is not correct when access after tableView is reloaded but if access one sec later it's giving the correct height. Is there any way to get correct height without waiting for a few sec.

self.tableView.reloadData()
self.tableViewHeight.constant = self.tableView.contentSize.height
self.containerSV.layoutIfNeeded()
like image 406
noob Avatar asked Sep 16 '25 01:09

noob


2 Answers

After reload correct contentSize will only be available once all the cells are loaded. You can use Key Value Observing for observing changes in content size.

// register observer 
tableView.addObserver(self, forKeyPath: "contentSize", options: [.new, .old, .prior], context: nil)

@objc override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {        
    if keyPath == "contentSize" {
         // content size changed
    }
}
like image 200
Bilal Avatar answered Sep 19 '25 23:09

Bilal


You can get correct contentSize without using KVO by doing this:

self.tableView.reloadData()
DispatchQueue.main.async {
   self.tableViewHeight.constant = self.tableView.contentSize
   self.containerSV.layoutIfNeeded()
}

As main queue is serial, task with getting contentSize to it will execute only when reloading tableview is finished.

like image 45
Alex Sh. Avatar answered Sep 19 '25 21:09

Alex Sh.