Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS message cell width/height using auto layout

The Goal

I'm trying to create a dynamic message cell using auto-layout.

enter image description here

What I've Tried

The cell is positioning correctly, for the most part, with auto-layout given the following constraints:

enter image description here

The Problem

My first problem was the message label (Copyable Label) width was constrained. That seems to be resolved by using setPreferredMaxLayoutWidth: as described in this question.

Height is still a problem. As you can see, the message bubble is still cutting off. In addition, I'm not sure how to determine the message cell height for the table view.

I expected auto-layout to somehow just work. I've read the answer here, but it seems like a lot to of steps.

The Question

First, is a case where auto-layout is more complex than traditional frame arithmetic?

Second, using auto-layout, how can I determine the height of the resulting cell?

like image 625
Jason McCreary Avatar asked Mar 22 '23 15:03

Jason McCreary


1 Answers

I fully use Auto Layout and what you speak about is kinda a problem. I didn't want to modify the way intrinsic size is calculated for performance purpose of UITable.

So I used a very simple way that is correct in the end. It's ok if your cell is simple, can become such hard if your cell contains more than one variable text.

I defined my cells normally, where you can put a UILabel that fits the insets (no problem about it). Then, in your table datasource, you define directly the height of the cell:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [TEXTOFYOURCELL sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(300, 1000)].height + 31; // Here it's defined for 15 of top and bottom insets, define +1 than the size of the cell is important.
}

EDIT : Here some code about the UILabel in the cell (in init method).

__titleLabel = [UILabel new];
__titleLabel.numberOfLines = 0;
[self.contentView addSubview:__titleLabel]; // adding to contentView rather than self is very important !
[__titleLabel keepInsets:UIEdgeInsetsMake(0, 15, 0, 15)];

I use this API : https://github.com/iMartinKiss/KeepLayout to manage auto layout simpler.

like image 87
Tancrede Chazallet Avatar answered Apr 26 '23 04:04

Tancrede Chazallet