0

I need to find table view content size because I need to increase table height based on number of rows. I used table view automatic dimension for automatically increase the cell height based cell contents. So I used to find table content size after table view loads completely then we can adjust the table view size.

I used below code for get the table view content size,

  Print(tableview.contentSize)

but it gives wrong size. So I have researched some links then I found this https://forums.developer.apple.com/thread/81895. In that link, you can see Apple says we need to mention estimated table height as 0 for get the correct table view content size. But it gives wrong content size again. For Example,

the table view load 5 rows and content size height was 100.0 means but it gives only 80.0. I don't know how to find the exact table view content size. Could you help on this ?

sarosar
  • 131
  • 1
  • 11

2 Answers2

3

You should make outlet for tableView height constraints and override updateViewConstraints() method inside your UIViewController.

override func updateViewConstraints() {
tableHeightConstraint.constant = tableView.contentSize.height
super.updateViewConstraints()

}

Thank you

Parth
  • 634
  • 8
  • 15
0

When you have any UIView inheriting UIScrollView you can easily get the updated contentSize under viewDidLayoutSubviews.

override func viewDidLayoutSubviews() {
    debugPrint("Updated Contensize \(tableView.contentSize)")
}
Sohil R. Memon
  • 9,404
  • 1
  • 31
  • 57
  • 2
    A scroll view's (as well as a table view's) content size has nothing to do with the size of the scroll view. The content size is not updated after `viewDidLayoutSubviews` of the view controller that contains the scroll view. A table view's content size is updated based on the currently known height of all rows, headers, and footers. That can change at any time independent of the view controller's views being laid out. – rmaddy Jan 30 '19 at 05:03
  • @rmaddy Yes, but any content changes or any new things updated, you can see that it will reflect in `viewDidLayoutSubviews`, I don't know but I am still using this in my code. Am I doing something wrong? – Sohil R. Memon Jan 30 '19 at 05:04
  • I need to find table vie content size after table view loads. So Currently I call the viewDidAppear to find the table view content size. It gives wrong size :( – sarosar Jan 30 '19 at 05:18
  • It should definitely work, as I have checked just now only. Have you applied constraint? – Sohil R. Memon Jan 30 '19 at 05:41