Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are the multiline UILabels in my UITableViewCell truncating on first load, but correcting themselves on scroll?

I’m having an issue with one of my tableviews in my app, and wonder if anyone has come across something similar. I have 2 labels in a custom tableviewcell – a questionLabel and an answerLabel – which have the following constraints:

enter image description hereenter image description here

On both UILabels I have the number of lines set to 0, to make them multi-line, and have added the preferredmaxLayoutWidthproperty to both too as follows:

cell.questionLabel.preferredMaxLayoutWidth = cell.questionLabel.frame.width
cell.answerLabel.preferredMaxLayoutWidth = cell.answerLabel.frame.width

I also have the following in the viewDidLoad() method, as per other StackOverflow suggestions:

self.faqTableView.rowHeight = UITableViewAutomaticDimension
self.faqTableView.estimatedRowHeight = 140.00

On first load, the labels are still becoming truncated, even though lines are set to 0, and weirdly at inconsistent places of the label. However, when scrolling the screen down and then back up to the top, the labels auto-correct themselves and the layout is perfect. See screenshot below:

enter image description here

Has anyone come across this issue before, and if so could you point me in the right direction. I'm not sure whether it's something I've failed to set, or a problem with my auto layout constraints.

like image 810
sixtysticks Avatar asked Feb 05 '18 11:02

sixtysticks


1 Answers

enter image description here

enter image description here

Add constraints like this. Delete the below lines

cell.questionLabel.preferredMaxLayoutWidth = cell.questionLabel.frame.width
cell.answerLabel.preferredMaxLayoutWidth = cell.answerLabel.frame.width
self.faqTableView.estimatedRowHeight = 140.00

Set the UILabel's number of lines to zero and implement the below method

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}
like image 121
Boudhayan Avatar answered Nov 03 '22 22:11

Boudhayan