Question

I'm using the following code to auto adjust the height of a label in a UITableView. It works the majority of the time, but certain times text is cut off. Is there something wrong with my code, or anything else I need to add?

UILabel *textLabel = ((UILabel *)[cell viewWithTag:3]);
textLabel.text = text;

CGSize maximumLabelSize = CGSizeMake(296, FLT_MAX);

CGSize expectedLabelSize = [text sizeWithFont:textLabel.font constrainedToSize:maximumLabelSize lineBreakMode:textLabel.lineBreakMode];

//adjust the label the the new height.
CGRect newFrame = textLabel.frame;
newFrame.size.height = expectedLabelSize.height;
textLabel.frame = newFrame;
Was it helpful?

Solution

In iOS 7 sizeWithFont: constrainedToSize: lineBreakMode: is deprecated, now you should use:

 CGSize maxSize = CGSizeMake(296.f, FLT_MAX);
 CGRect labRect = [someText boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:textLabel.font} context:nil];


 textLabel.frame = CGRectMake(0, 0, maxSize.width, labRect.size.height);
 textLabel.text = someText;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top