首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何计算iOS 6中给定宽度的NSAttributedString的高度?

如何计算iOS 6中给定宽度的NSAttributedString的高度?
EN

Stack Overflow用户
提问于 2018-03-12 05:34:08
回答 1查看 0关注 0票数 0

现在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高度的东西。
代码语言:javascript
运行
复制
    NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] init];
    NSDictionary * attributes = @ {NSFontAttributeName:[UIFont fontWithName:@“HelveticaNeue”size:15],NSForegroundColorAttributeName:[UIColor blueColor]};
    [assignedString appendAttributedString:[[NSAttributedString alloc] initWithString:@“Attributed String \ n”attributes:attributes]];
    [assignedString appendAttributedString:[[NSAttributedString alloc] initWithString:@“Attributed String \ n”attributes:attributes]];
    [assignedString appendAttributedString:[[NSAttributedString alloc] initWithString:@“Attributed String \ n”attributes:attributes]];
    [assignedString appendAttributedString:[[NSAttributedString alloc] initWithString:@“Attributed String \ n”attributes:attributes]];
    [assignedString 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。

EN

回答 1

Stack Overflow用户

发布于 2018-03-12 14:48:34

代码语言:txt
复制
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包含字体属性。如果没有字体,就无法正确计算大小。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100007587

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档