MrTourkos
MrTourkos

Reputation: 1952

Multiple UILabels in UITAbleViewCell with dynamic height

In an empty UITableViewCell i have two UILabels aligned like this: |--label1----label2--|. Both of them will be populated dynamically. I need to set the constraints in a way that both labels remain center-aligned but the cell's height be determined by the label that has the most content. So far:

Upvotes: 2

Views: 2740

Answers (1)

user4151918
user4151918

Reputation:

Add a (lower priority) fixed height constraint for the cell (e.g. = 40).

Add a top and bottom constraint for each label. Make the top constraint a fixed margin (e.g. = 8). Make the bottom constraint a (higher priority) greater than or equal constraint (e.g. >= 8).

The cell's height will be determined by the taller label, and all the other vertical constraints will still be met.

Update:

It turns out that you don't need a fixed height constraint for the cell, or even need to tweak the horizontal content hugging or compression resistance priorities.

I pinned the labels' top and left or right edge to the superview.margin, = 0, and added a horizontal space between the labels >= 4.

I pinned the labels' bottom edge to the superview.margin, >= 0. I also set both labels' vertical compression resistance priority to 1000.

At this point, we've set the minimum necessary constraints. However, if both labels are long, one label will take most of the width, forcing the other label to be extremely narrow. I arbitrarily added a width >= 100 constraint to both labels to balance things out.

Label constraints

Enable self-sizing in -viewDidLoad, then assign your labels' text, and have the cell lay itself out. It wasn't necessary to override anything in the custom UITableViewCell.

self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 44.0;

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

     cell.leftLabel.text = ...;
     cell.rightLabel.text = ...;

     [cell setNeedsLayout];
     [cell layoutIfNeeded];

     return cell;
}

Snapshot of tableView with dynamic side-by-side labels

Upvotes: 5

Related Questions