1

I'm seeing lots of deprecated answers for this question:

How do I calculate the number of lines in use in a UILabel based of its set text?

I know that I need to set the UILabel to have bounds that resize with word wrapping. In this way, I could detect the height of my UILabel and adjust an NSLayoutConstraint for the height of my UITableViewCell. Basically my problem plain and simple is:

How can I determine my UILabel's number of lines in use(based of descriptionLabel.text) or height in order to resize My UITableView's UITableViewCells which contain my UILabel.

Currently I have used this code:

descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 30, 270, 65)];
descriptionLabel.textColor = [UIColor blackColor];
descriptionLabel.numberOfLines = 0;
descriptionLabel.adjustsFontSizeToFitWidth = YES;
Chisx
  • 1,976
  • 4
  • 25
  • 53
  • what do you mean by "calculate"? You don't *calculate* it, you *set* it. – The Paramagnetic Croissant Jun 28 '15 at 06:25
  • Sorry what I mean is calculate the number of lines in use. As in, the number of lines that the length of `descriptionLabel.text` creates. – Chisx Jun 28 '15 at 06:26
  • is [this](https://stackoverflow.com/questions/1085524/how-to-count-the-number-of-lines-in-an-objective-c-string-nsstring/30040905#30040905) what you are looking for? – The Paramagnetic Croissant Jun 28 '15 at 06:28
  • I don't believe so. I'm looking for a SIMPLE solution that would involve using only the UILabel. I will default to attempting this string method if this is too complicated. I feel like this should be easy. – Chisx Jun 28 '15 at 06:32
  • @Chisx I think you don't need to get the number of lines. Instead, you can calculate the height what the label need – Bannings Jun 28 '15 at 07:53

2 Answers2

0

Try using the following code

NSAttributedString *attrStr = ... // your attributed string
CGFloat width = 300; // whatever your desired width is
CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(width, 10000) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
//rect is the height of UILABEL which u can used as height of label or table view row or etc
Nischal Hada
  • 3,230
  • 3
  • 27
  • 57
  • Does it have to be an `NSAttributedString`? Or can I accomplish the same effect by simply placing my NSString in the line where you create the variable `CGRect rect` – Chisx Jun 28 '15 at 18:24
  • it must be NSAttributedString you can place your string in NSAttributedString – Nischal Hada Jun 29 '15 at 04:04
0

I solved my problem very simply with this code:

CGSize maxSize = CGSizeMake(290.0f, CGFLOAT_MAX);
CGSize requiredSize = [descriptionLabel sizeThatFits:maxSize];
[descriptionLabel setFrame:CGRectMake(15, 50, requiredSize.width, requiredSize.height)];
NSLog(@"THE HEIGHT OF THIS DESCRIPTIONLABEL IS: %f",cell.frame.size.height);
Chisx
  • 1,976
  • 4
  • 25
  • 53