Im quite new to iOS development and i've been stuck with this for a couple of days
i have a UITableView
and UIImageView
inside a UIScrollView
, the UIImageView
is on top of the table and the height is static so i don't have any issues with that, the problem is the UITableView
, i need to get the height dynamically based on the content and set that height to a height constraint of the table and the contentsize of the scrollview.
The cells are self sizing, so the height of the cell varies depending on the content. The best i could do so far is getting the height by using contentSize.height
property of UITableView
but apparently this returns a height based on the estimatedRowHeight
i set, not te actual height of each row.
the code:
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
tableView.estimatedRowHeight = rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
tableView.layoutIfNeeded()
tableHeight.constant = tableView.contentSize.height
scrollView.contentSize.height = imageView.bounds.height + tableView.contentSize.height
}
What i've tried:
- Getting the height by using
contentSize.height
property ofUITableView
, as shown in the code and explained before. Getting the height of each row individually on
willDisplayCell
and add it to the height constraint of the table and the contentSize of the scrollview. But looks like this adds more rows than actually are, giving me a bunch of empty cells at the end of the table. the code insidewillDisplayCell
:let cellHeight = cell.bounds.height tableHeight.constant += cellHeight scrollView.contentSize.height += cellHeight
The same as before, except i tried inside
cellForRowAtIndexPath
with the same result.