【发布时间】:2014-05-25 04:02:03
【问题描述】:
CoreText 没有给出属性字符串的正确高度(短了一行或更多)。我在 SO 上看到了很多关于此的帖子,但无法理解或找到解决方案。有人可以解释 Core Text 高度计算是如何工作的吗?这是我编写的示例代码,显示了不准确的高度计算。
上下文
我有一个集合视图,其中单元格的高度由其中的内容决定。 我在单元格中显示文本段落。我想通过使用核心文本进行高度计算来节省一些性能。我已经看到,通过核心文本的高度计算,我可以节省大约 300 毫秒。
代码
//高度计算
+ (CGFloat)getHeight
{
NSString *text = @"The Apple HIG recommends to use a common color for links and buttons and we did just that. By using the same color throughout the app we trained the user to always associate blue to a link.The Apple HIG recommends to use a common color for links and buttons and we did just that.By using the same color throughout the app we trained the user to always associate blue to a link.";
NSAttributedString *attrStr = [self attributedString:text withLinespacing:3 withLineBreakMode:NSLineBreakByWordWrapping];
CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)(attrStr));
CGSize suggestedSize = CTFramesetterSuggestFrameSizeWithConstraints(frameSetter,
CFRangeMake(0, attrStr.length),
NULL,
CGSizeMake(320, 9999),
NULL);
return suggestedSize.height;
}
// Cell 即将显示时加载相同的文本
- (void)loadData
{
NSString *text = @"The Apple HIG recommends to use a common color for links and buttons and we did just that.By using the same color throughout the app we trained the user to always associate blue to a link.The Apple HIG recommends to use a common color for links and buttons and we did just that.By using the same color throughout the app we trained the user to always associate blue to a link.";
NSAttributedString *attrStr = [[self class] attributedString:text withLinespacing:3 withLineBreakMode:NSLineBreakByWordWrapping];
// UILabel element
self.textLabel.attributedText = attrStr;
self.layer.borderColor = [UIColor blueColor].CGColor;
self.layer.borderWidth = 1.0f;
}
// 生成带前导、字体和换行符的属性字符串
+ (NSAttributedString *)attributedString:(NSString *)string
withLinespacing:(CGFloat)linespacing
withLineBreakMode:(NSLineBreakMode)lineBreakMode
{
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:string];
NSInteger strLength = [string length];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
style.lineSpacing = linespacing;
style.lineBreakMode = lineBreakMode;
[attrStr addAttributes:@{NSParagraphStyleAttributeName: style,
NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:15]} range:NSMakeRange(0, strLength)];
return attrStr;
}
上面的代码使用core text计算高度和UILabel来显示文本。 UILabel 对单元格 {Top:17, Leading:13px, Trailing:13px}
有 3 个约束【问题讨论】:
标签: ios objective-c uicollectionview core-text