swiftuitableviewstoryboarduistackviewuitableviewautomaticdimension

UItableView automaticDimension not working with UIStackView


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:

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
    }
}

The cell's xib file: The cell's xib file

Result with Less Than or Equal bottom constraint:

Result with Less Than or Equal bottom constraint

Result with Greater Than or Equal or Equal bottom constraint:

Result with Greater Than or Equal or Equal bottom constraint


Solution

  • 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