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 toUITableView.automaticDimension
.- To not implement function
heightForRowAt
. TableViewCell
Row Height
is set toAutomatic
in the xib file.- All views are constrained vertically.
- To play with
UIStackView
distribution
property. - To set the
UIStackView
bottom constraint to thesuperView
toLess Than or Equal
(with this items are too tiny and withGreater Than or Equal
, orEqual
, item's height is equal to screen width since they haveaspect ratio
1:1 - To play with
Content Hugging Priority
andContent 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: