如何在iOS 6中计算具有给定宽度的NSAttribute字符串的高度[重复]

这个问题在这里已经有答案了

8年前关闭的

可能重复:
如何以固定宽度获取NSAttribute字符串的高度

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

要计算NSAttribute字符串的图形大小,有两种方法可用:

  1. -(CGSize)size无法使用,因为它没有考虑任何宽度
  2. 我尝试了-(CGRect)boundingrectiwithsize:(CGSize)size选项:(NSStringDrawingOptions)选项上下文:(NSStringDrawingContext*)上下文,但不知怎的,它没有给我正确的高度。我认为这个方法有缺陷。如果我运行以下代码,它会给出边界大小:572.324951,19.000000忽略给定的宽度200。它应该给我大约100的高度
NSMutableAttributedString*attributedString=[[NSMutableAttributedString alloc]init];
NSDictionary*[email protected]{NSFontAttributeName:[UIFontFontWithName:@“HelveticaNeue”大小:15],NSForegroundColorAttributeName:[UIColor blueColor]};
[attributedString AppendedAttributedString:[[NSAttributedString alloc]initWithString:@“属性字符串\n”属性:属性]];
[attributedString AppendedAttributedString:[[NSAttributedString alloc]initWithString:@“属性字符串\n”属性:属性]];
[attributedString AppendedAttributedString:[[NSAttributedString alloc]initWithString:@“属性字符串\n”属性:属性]];
[attributedString AppendedAttributedString:[[NSAttributedString alloc]initWithString:@“属性字符串\n”属性:属性]];
[attributedString AppendedAttributedString:[[NSAttributedString alloc]initWithString:@“属性字符串\n”属性:属性]];
CGRect frame=[attributedString BoundingDirectWithSize:CGSizeMake(2001000)选项:0上下文:nil];
NSLog(@“边界大小:%f,%f”,frame.size.width,frame.size.height);

Mac OS X还有其他可用的方法,但不适用于iOS

选项2在具有适当参数的iOS中确实有效

nsattributestring*attrStr=…//您的属性字符串
CGFloat宽度=300;//你想要的宽度是多少
CGRect rect=[attrStr boundingRectWithSize:CGSizeMake(宽度,10000)选项:NSStringDrawingUserLineFragmentOrigin | NSStringDrawingUserFontLeading上下文:nil];

如果选项参数没有正确的值,您将获得错误的高度

还要求attrStr包含字体属性。没有字体,就无法正确计算大小

发表评论