Thiêm Thiêm - 4 months ago 20
iOS Question

iOS UILabel width doesn't fit inside table cell

I'm new to iOS development. I have an issue when trying to put labels inside uitableviewcell. The text keeps going out of the cell. I add all needed constraints but it doesn't work.
Here is my setup and code:

Title label attributes: Number of lines-0, Line breaks-Word wrap


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


UILabel *titleLabel = (UILabel*)[cell viewWithTag:100];
titleLabel.text = @"Why does this long text get out of the cell? The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.";

I'm using xcode 6.2 and ios 8.2.

Thanks for any help.


enter image description here

Cell prototype:
enter image description here

Title label constraints:

enter image description here


You need to do two things in order to keep your text inside the label boundries and in cell.

  1. If the width of label is fixed then in that case your cell's height depends on the height of the label(which is derived from it's content). As you have already provided the estimatedRowHeight and rowHeight as UITableViewAutomaticDimension. So this is OK.
  2. The width of the label should be limited before/ till it reaches the extreme right of the cell. Also please ensure that the if the label's width is flexible then it should also be hooked from the right side as well.

Alternatively you could write code using below API to calculate the label's height based on the content of the label. This will determine the height of the cell. And finally while creating the cell assign the text to the label.

For iOS 7 and above:

#define LABELS_MAX_HEIGHT             10000.0f

CGSize constraintSize = CGSizeMake(label.frame.size.width, LABELS_MAX_HEIGHT);

NSAttributedString *attributedText = [[[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: label.font}] autorelease];
        CGRect rect = [attributedText boundingRectWithSize:constraintSize
        strSize = rect.size;