noob
noob

Reputation: 555

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()

Upvotes: 4

Views: 4780

Answers (2)

Alex Sh.
Alex Sh.

Reputation: 629

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.

Upvotes: 1

Bilal
Bilal

Reputation: 19156

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
    }
}

Upvotes: 8

Related Questions