可能重复:
How to get height for NSAttributedString at a fixed width
现在,iOS 6中提供了NSAttributedString。出于布局目的,我想知道如何在固定宽度下计算NSAttributedString所需的高度。我正在寻找的东西相当于NSString的- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size
但是对于NSAttributedString。
要计算NSAttributedStrings的绘图大小,有两种方法可用:
- (CGSize)size
无法使用,因为它不考虑任何宽度。- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options context:(NSStringDrawingContext *)context
,但不知怎的,它没有给我正确的高度。我觉得这个方法很麻烦。如果我运行以下代码,它会让我bounding size: 572.324951, 19.000000
忽略200的给定宽度。它应该给我100个高度。NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init]; NSDictionary *attributes = @{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue" size:15], NSForegroundColorAttributeName : [UIColor blueColor]}; [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@"Attributed String\n" attributes:attributes]]; [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@"Attributed String\n" attributes:attributes]]; [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@"Attributed String\n" attributes:attributes]]; [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@"Attributed String\n" attributes:attributes]]; [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@"Attributed String\n" attributes:attributes]]; CGRect frame = [attributedString boundingRectWithSize:CGSizeMake(200, 1000) options:0 context:nil]; NSLog(@"bounding size: %f, %f", frame.size.width, frame.size.height);
Mac OS X还有其他可用的方法,但不适用于iOS。
答案 0 :(得分:165)
选项2在iOS中可以使用适当的参数。
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];
如果没有options
参数的正确值,您将得到错误的高度。
还需要attrStr
包含字体属性。没有字体,就无法正确计算尺寸。