As indicated, this post describes how to get the height, not the number of rows. To get the number of rows,
- Get the height for a single letter, for example.
@"A" . - Divide the row height by the height obtained at 1 above.
eg.
CGFloat unitHeight = [@"A" heightForWidth:width usingFont:font]; CGFloat blockHeight = [text heightForWidth:width usingFont:font]; NSInteger numberOfLines = ceilf(blockHeight / unitHeight);
Starting with iOS 7, the way to get the mark of the desired height has changed. To get the height, you can use the following code:
NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init]; CGSize labelSize = (CGSize){width, FLT_MAX}; CGRect r = [self boundingRectWithSize:labelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: font} context:context];
where is the height of r.size.height . Please note that font must be provided. You can put this in a category for NSString for convenience, for example.
@implementation NSString (HeightCalc) - (CGFloat)heightForWidth:(CGFloat)width usingFont:(UIFont *)font { NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init]; CGSize labelSize = (CGSize){width, FLT_MAX}; CGRect r = [self boundingRectWithSize:labelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: font} context:context]; return r.size.height; } @end
(Memory management if ARC is not used, by the way.)
For iOS 6 and below:
Say you have UILabel *myLabel and you want to know the height of the label (with some tweaking, you can get # lines by dividing the height with some corresponding number, which depends on the font size).
UILabel *myLabel; CGSize labelSize = [myLabel.text sizeWithFont:myLabel.font constrainedToSize:myLabel.frame.size lineBreakMode:UILineBreakModeWordWrap]; CGFloat labelHeight = labelSize.height;
Hope this helps. If this does not help, let me know and I will dig further. Also, unverified code, but worked with a link.
For a more complete example, here is the code I entered in the viewDidLoad: method for a view controller:
[super viewDidLoad]; UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50,50,200,350)]; myLabel.numberOfLines = 0; myLabel.lineBreakMode = UILineBreakModeWordWrap; myLabel.text = @"This is some text in a UILabel which is long enough to wrap around the lines in said UILabel. This is a test, this is only a test."; [self.view addSubview:myLabel]; CGSize labelSize = [myLabel.text sizeWithFont:myLabel.font constrainedToSize:myLabel.frame.size lineBreakMode:UILineBreakModeWordWrap]; CGFloat labelHeight = labelSize.height; NSLog(@"labelHeight = %f", labelHeight); [myLabel release];
Exiting NSLog is:
2010-11-15 18:25:27.817 so_labelheight[728:307] labelHeight = 126.000000