When Does a Uitableview's Contentsize Get Set

When does a UITableView's contentSize get set?

You can make the UITableView calculate the size of the content immediately by calling layoutIfNeeded on the UITableView. This will run all the necessary calculations to layout the UITableView.

Example for a UITableViewController subclass that you want to put in a container view with variable size:

Objective-C

- (CGSize)preferredContentSize
{
// Force the table view to calculate its height
[self.tableView layoutIfNeeded];
return self.tableView.contentSize;
}

Swift

override var preferredContentSize: CGSize {
get {
// Force the table view to calculate its height
self.tableView.layoutIfNeeded()
return self.tableView.contentSize
}
set {}
}

UITableView content size while using auto-layout

Finally I am solved my problem with some tweak. I changed tableview height to max (Objective-C: CGFLOAT_MAX, Swift: CGFloat.greatestFiniteMagnitude) before reloading data on table, so tableview has space to resize all cells.

Objective-C:

self.tableHeightConstraint.constant = CGFLOAT_MAX;
[self.tableView reloadData];
[self.tableView layoutIfNeeded];
self.tableHeightConstraint.constant = self.tableView.contentSize.height;

Swift:

tableHeightConstraint.constant = CGFloat.greatestFiniteMagnitude
tableView.reloadData()
tableView.layoutIfNeeded()
tableHeightConstraint.constant = contentTableView.contentSize.height

Posting this so it will be helpful for others.

uitableview content size is not returning correctly swift

I tried reloadData() and layoutIfNeeded() and tried many different ways. nothing has worked for me. Finally I solved it by using KVO.

Here is my code

override  func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.instructiontableview.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)

}
override func viewWillDisappear(_ animated: Bool) {
self.instructiontableview.removeObserver(self, forKeyPath: "contentSize")
super.viewWillDisappear(true)
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?){
if(keyPath == "contentSize"){

if let newvalue = change?[.newKey]{
let newsize = newvalue as! CGSize
self.heightofinstructioncontainerview.constant = newsize.height
}
}
}

UITableView contentSize does not updated

The best solution I've found. This is to do the calculation of height manually, without using UITableViewAutomaticDimension.

Yes, you have to spend a time for writing this.

After each added element of the UICollectionViewCell, you need to make an update your tableView (depending on what suits you):

  • reloadRows(at:with:)
  • reloadSections(_:with:)
  • reloadData()


Related Topics



Leave a reply



Submit