0

I have UITableViewCell with multiple components act as rows, consist of mix elements of UILabel, UIView and UIStackView inside UIView.

enter image description here

Each component inside the cell has height constraint. I want the height of the cell to be dynamic by setting the constant of the height constraint zero or 21 at runtime, depend or whether it has content to show.

// more codes like below    
if let mealPref = passenger.mealPref {
    mealPrefHeight.constant = 21
    let title = R.string.localizable.meal_request.localized()
    mealPrefLabel.text = "• \(title): \(mealPref)"
} else {
    mealPrefHeight.constant = 0
}
// more codes like above

It doesn't work.

I have similar problem back then, but I think it's different case. I've read this, this and this.

enter image description here

enter image description here

Seto
  • 1,234
  • 1
  • 17
  • 33
  • If you change `constant ` of a constraint at run time `AutomaticDimension` won't work. If you set constant = 21 then automatic dimension will be overwritten. – Gokul G Jan 03 '18 at 04:55

3 Answers3

1

Did you added in viewDidLoad

tableView.estimatedRowHeight = 44 // for assumption
tableView.rowHeight = UITableViewAutomaticDimension
iOS Geek
  • 4,825
  • 1
  • 9
  • 30
0

try removeing height contraint.

if let mealPref = passenger.mealPref {
   let title = R.string.localizable.meal_request.localized()
   mealPrefLabel.text = "• \(title): \(mealPref)"
 }  
Shezad
  • 756
  • 7
  • 14
0

You can simply change the UITableViewCell's height in UITableViewDelegate method:

optional func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat

Example:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
    if indexPath.row == 0
    {
        return 126.0
    }
    else
    {
        return 90.0
    }
}

You can change the height according to your requirement. Here I just used the row number to make the height changes.

Screenshot:

enter image description here

PGDev
  • 23,751
  • 6
  • 34
  • 88