现在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]};
[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。
发布于 2018-03-12 14:48:34
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
包含字体属性。如果没有字体,就无法正确计算大小。
https://stackoverflow.com/questions/-100007587
复制相似问题