Home > database >  Tableview cell automaticDimension for 3 labels with one container view
Tableview cell automaticDimension for 3 labels with one container view

Time:12-09

enter image description here

The white background is my cell super view and the blue background view is the container view. The container view is connected with the super view with the following constraints.

Top space to super view: 25, Bottom space to super view: 12

In the container view (Blue view) there are 3 labels. Weekly plan, Monthly plan, Save about...

The Weekly plan label has a height constraint of height >= 22 and it has a top space with its container view (Blue view) which is 16 and the bottom space with the monthly label is 10. The monthly view has a 0 bottom constraint with the save about label. And finally the save about label has 12 bottom constraints with the container view.

These 3 labels could have multiple lines and I need to show them accordingly. If one line then it will show in 1 line if multiple lines then it will show all text in multiple lines.

Right now I am trying to show them with UITableView.automaticDimension inside of the table view heightForRowAt delegate.

case .weeklyPlan, .monthlyPlan, .annualPlan: return UITableView.automaticDimension

But it's not updating all cells properly. I didn't set any estimated row hight or any other height ratio in my view did load. What I am missing here? Thanks!

CodePudding user response:

in order to make it work, you should use preferredMaxLayoutWidth on the labels. This property set the preferred maximum width for a multiline label.

This would be an example on what you should put in the tableViewCell awakeFromNib() method.

    titleLabel.numberOfLines = 0
    subtitleLabel.numberOfLines = 0
    descriptionLabel.numberOfLines = 0
    titleLabel.preferredMaxLayoutWidth = frame.width
    subtitleLabel.preferredMaxLayoutWidth = frame.width
    descriptionLabel.preferredMaxLayoutWidth = frame.width

    containerView.clipsToBounds = true
    containerView.layer.cornerRadius = 16
    containerView.backgroundColor = .cyan

CodePudding user response:

If I understood the problem correctly, I tried to load such a code.

TableViewCell:

  • Labels -> numberOfLines = 0
  • StackView -> Distribution And Alignment = fill

enter image description here

ViewController: enter image description here

Result: enter image description here

CodePudding user response:

First make numberOfLines = 0 to your labels and if you dont make any constraint (leading , trailing) to your labels even if you set numberOfLines to 0 the texts will not go into the 2nd paragraph.Texts will overflow from the label , you will see it with three dots at the point where it overflows.

It's hard to tell without seeing the code but giving leading and trailing constraints will fix your issue.

  • Related