I want that my UITableViewCell
calculates properly its height so its bottom matches the UIStackView
bottom.
I have an understanding that for UITableView.automaticDimension
to work you need to set all the vertical constraints of the UITableViewCell
so it can calculate its height.
That's what I'm failing to do. I've made a test project in which I made sure of:
tableView.rowHeight
property is set to UITableView.automaticDimension
.heightForRowAt
.TableViewCell
Row Height
is set to Automatic
in the xib file.UIStackView
distribution
property.UIStackView
bottom constraint to the superView
to Less Than or Equal
(with this items are too tiny and with Greater Than or Equal
, or Equal
, item's height is equal to screen width since they have aspect ratio
1:1Content Hugging Priority
and Content Compression Resistance Priority
. In the test all views have default values, for hugging horizontal and vertical 250, and for compression horizontal and vertical 750.The code:
import Foundation
import UIKit
class IBAutomaticDimensionTableViewViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet private weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableView.automaticDimension
tableView.register(
IBAutomaticDimensionTableViewCell.nib,
forCellReuseIdentifier: IBAutomaticDimensionTableViewCell.nibName
)
tableView.delegate = self
tableView.dataSource = self
tableView.reloadData()
// view.layoutIfNeeded() Not working with or without it
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: IBAutomaticDimensionTableViewCell.nibName,
for: indexPath
) as! IBAutomaticDimensionTableViewCell
return cell
}
}
Result with Less Than or Equal
bottom constraint:
Result with Greater Than or Equal
or Equal
bottom constraint:
The issue was the aspect ratio constraints. It seems that they are prioritizing width over height (that's weird to me since height is a constant value and I would expect for it to be prioritized over a calculated one, but Apple thought differently)
In Android you can specify which one has preference (width or height), I don't know a way here (playing with aspect ratio constraints' relation didn't solve it)
Replacing aspect ractio constraints for the hardcoded width values (32 first view and 20 for the rest) solved it