62

可能重复:
如何以固定宽度获取 NSAttributedString 的高度

现在 NSAttributedString 在 iOS 6 中可用。出于布局目的,我想知道如何计算 NSAttributedString 在固定宽度下所需的高度。我正在寻找与 NSString 等效- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size但适用于 NSAttributedString 的东西。

要计算 NSAttributedStrings 的绘图大小,有两种方法可用:

  1. - (CGSize)size不能使用,因为它没有考虑任何宽度。
  2. 我试过- (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。

4

1 回答 1

175

选项 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包含字体属性。没有字体,就无法正确计算大小。

于 2013-01-19T00:59:43.870 回答