现在 NSAttributedString 在 iOS 6 中可用。出于布局目的,我想知道如何计算 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(@"边界大小: %f, %f", frame.size.width, frame.size.height);
Mac OS X 还有其他可用的方法,但不适用于 iOS。