swiftautolayouttableview

TableView AutomaticDemension doesn't work(Swift


I wanted to adjust my tableview cell height, so I wrote this code :

self.tableView.rowHeight = UITableView.automaticDimension
self.tableView.estimatedRowHeight = 200

But it failed due to my poor autolayout. I have no idea what the problem is. Below is my autolayout code of the tableview cell.

 NSLayoutConstraint.activate([
            numberImageView.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 20),
            numberImageView.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 10),
            numberImageView.heightAnchor.constraint(equalToConstant: 20),
            numberImageView.widthAnchor.constraint(equalToConstant: 20),
            
            descriptionLabel.leadingAnchor.constraint(equalTo: numberImageView.trailingAnchor, constant: 15),
            descriptionLabel.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -15),
            descriptionLabel.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 10),
            
            descriptionImageView.centerXAnchor.constraint(equalTo: self.centerXAnchor),
            descriptionImageView.topAnchor.constraint(equalTo: descriptionLabel.bottomAnchor, constant: 10),
            descriptionImageView.heightAnchor.constraint(equalToConstant: 100),
            descriptionImageView.widthAnchor.constraint(equalToConstant: 100),
        ])

I tried to find the missing constraints, but I think there is no problem.


Solution

  • None of the views added are pinned to bottom of the view, In order for a view to be able to calculate it's height based on content inside, there must be a ladder of constraints which connects it from top to bottom. In your case if you add bottom constraint, Your cell will be able to get dynamic height.

    try adding this constraint at the end of your array

    descriptionImageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0)
    

    It will pin the imageview to bottom as well. So the hierarchy will be TopAnchor -> DescriptionLabel -> DescriptionImageView -> BottomAnchor