Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating number of lines of dynamic UILabel (iOS7)

Tags:

ios

uilabel

ios7

There are many solutions to this questions arround but couldn't find non-deprecated one.

I have an UILabel with mode WordWrap and fixed width of, let's say 250. Lines are set to 0.

Here is what I tried:

UILabel *contentLabel = (UILabel*)[contentView viewWithTag:10];
CGSize size = [contentLabel.text sizeWithFont:contentLabel.font forWidth:contentLabel.frame.size.width lineBreakMode:NSLineBreakByWordWrapping];
NSLog(@"Label's height is: %d", size.height);

The output of height param is always 20 (so it's like one line), while te text is like 30 lines long.

I need that for UIScrollView purposes.

like image 968
Jacek Kwiecień Avatar asked Sep 13 '13 10:09

Jacek Kwiecień


People also ask

How is UILabel height calculated?

To summarize, you can calculate the height of a label by using its string and calling boundingRectWithSize . You must provide the font as an attribute, and include . usesLineFragmentOrigin for multi-line labels.

How do I change label height in Swift?

To give a dynamic height to an UIlabel in swift we can use the frame property of UILabel. We can create a frame using the CGRect which allows us to give different variables like x position, y position, width, and height.


1 Answers

Use suggested in documentation method :

- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context NS_AVAILABLE_IOS(7_0);

E.g.

    CGSize maxSize = CGSizeMake(self.label.frame.size.width, MAXFLOAT);

    CGRect labelRect = [self.label.text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.label.font} context:nil];

    NSLog(@"size %@", NSStringFromCGSize(labelRect.size));
like image 118
Numeral Avatar answered Oct 10 '22 10:10

Numeral