0

我使用 CTFramesetterSuggestFrameSizeWithConstraints 函数来定义大小,我的属性字符串将需要,但我得到的高度比它应该的要小,宽度也比 constrainSize.width 参数大。这是我的代码:

CTTextAlignment textAlignment = kCTLeftTextAlignment;
CTLineBreakMode lineBreakMode = kCTLineBreakByWordWrapping;

CTParagraphStyleSetting paragraphSettings[] = {
    {
        kCTParagraphStyleSpecifierAlignment,
        sizeof(textAlignment),
        &textAlignment
    },
    {
        kCTParagraphStyleSpecifierLineBreakMode,
        sizeof(lineBreakMode),
        &lineBreakMode
    }  
};

CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(paragraphSettings, sizeof(paragraphSettings) / sizeof(paragraphSettings[0]));

NSMutableAttributedString *attrString = [[[NSMutableAttributedString alloc] initWithString:[authorString stringByAppendingFormat:@" %@", bodyText]] autorelease];

CTFontRef ctfontAuthor = CTFontCreateWithName((CFStringRef)@"Arial-BoldMT", 14.0, NULL);
CTFontRef ctfontBody = CTFontCreateWithName((CFStringRef)@"Arial", 14.0, NULL);
[attrString addAttribute:(NSString *)kCTParagraphStyleAttributeName value:(id)paragraphStyle range:NSMakeRange(0, [attrString length])];
[attrString addAttribute:(NSString *)kCTFontAttributeName value:(id)ctfontAuthor range:NSMakeRange(0, [authorString length] + 1)];
[attrString addAttribute:(NSString *)kCTFontAttributeName value:(id)ctfontBody range:NSMakeRange([authorString length] + 1, [bodyText length])];
CFRelease(ctfontAuthor);
CFRelease(ctfontBody);
CFRelease(paragraphStyle);

CFRange fitRange;
CGSize result = CGSizeZero;
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFMutableAttributedStringRef)attrString);
result = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, [authorString length] + [bodyText length] + 1), NULL, size, &fitRange);
CFRelease(framesetter);
return result;// result is the value I need to be constrained to size (229.0, MAXFLOAT) but sometimes it is 231 and some more

我究竟做错了什么?

4

3 回答 3

0

在返回结果大小之前,尝试将 result.width 参数设置为约束大小的宽度。

于 2013-01-10T11:26:50.693 回答
0

我也在这种情况下运行,解决了它并编写了一个类别,在所有情况下都适用于我。如果您使用零作为高度,请参阅我的答案,它不会将高度限制为任何高度。我为这个问题写了一个类别,在所有情况下都对我有用。查看iOS UITableView 与动态文本和图像一起呈现(NSAttributedString + 图像)

于 2014-03-09T02:42:12.783 回答
0

我遇到了类似的问题,我从这篇文章中找到了解决方案(至少对于高度问题)。您需要指定一个 kCTParagraphStyleSpecifierLineSpacingAdjustment。

于 2012-07-13T13:56:56.857 回答