简体   繁体   中英

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);

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM