Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSAttributedString multiline giving wrong height?

I want to calculate the height of NSAttributedString Multiline. It is working fine for single line (means it is minus the leading from the height). but if the text is multiline it is giving the same as single line.

NSMutableParagraphStyle *titleParagraphStyle = [[NSMutableParagraphStyle alloc] init];
titleParagraphStyle.lineHeightMultiple = 0.9f;
titleParagraphStyle.lineBreakMode = NSLineBreakByWordWrapping;

CGSize constrainedSize = CGSizeMake(TOUNameWidth, MAXFLOAT); 

NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                      TOUNameFont, NSFontAttributeName,
                                      titleParagraphStyle, NSParagraphStyleAttributeName,
                                      nil];

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString: name attributes:attributesDictionary];


CGRect rect = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesFontLeading context:nil];

NSLog(@"rect is %f",rect.size.height);
like image 990
Priyanka Chhetri Avatar asked Jul 23 '13 16:07

Priyanka Chhetri


1 Answers

As per the documentation of boundingRectWithSize:options:context: you need to add NSStringDrawingUsesLineFragmentOrigin

If NSStringDrawingUsesLineFragmentOrigin is not specified, the rectangle’s height will be ignored and the operation considered to be single-line rendering. (Due to a bug, the width is also ignored on iOS 6.)

like image 198
Patrick Tescher Avatar answered Sep 19 '22 23:09

Patrick Tescher