如何获得适合受限大小的字符串,如UILabel

时间:2013-02-01 14:25:32

标签: string text size uilabel truncate

我有一个非常长的文本,所以我不想使用UITextView,而是将文本截断为小块,这些小块可以适合宽度和高度为300,400的标签,并且基于块的数量,我想要动态创建UILabel并用这些块填充它们。

我编写了一个方法,但它似乎没有返回适合的实际字符串。它返回较短的字符串。

我错过了什么吗? 无论如何我能做到吗?

- (NSArray *)truncate:(NSString *)text
{
    NSMutableArray *textChunks = [[NSMutableArray alloc] init];

    NSString *chunk = [[NSString alloc] init];

    CTFramesetterRef frameSetter;
    UIFont *uiFont = [UIFont systemFontOfSize:17.0f];
    CTFontRef ctFont = CTFontCreateWithName((__bridge CFStringRef)uiFont.fontName, uiFont.pointSize, NULL);
    NSDictionary *attr = [NSDictionary dictionaryWithObject:(__bridge id)ctFont forKey:(id)kCTFontAttributeName];
    NSMutableAttributedString *attrString  = [[NSMutableAttributedString alloc] initWithString:text attributes:attr];

    CFRange fitRange;
    while (attrString.length>0) {

        frameSetter = CTFramesetterCreateWithAttributedString ((__bridge CFAttributedStringRef) attrString);
           CGSize framSize = CTFramesetterSuggestFrameSizeWithConstraints(frameSetter, CFRangeMake(0,0), NULL, CGSizeMake(myLabel.frame.size.width, myLabel.frame.size.height), &fitRange);
        NSLog(@"height: %f", framSize.height);
        CFRelease(frameSetter);

       chunk = [[attrString attributedSubstringFromRange:NSMakeRange(0, fitRange.length)] string];

        [textChunks addObject:chunk];

        [attrString setAttributedString: [attrString attributedSubstringFromRange:NSMakeRange(fitRange.length, attrString.string.length-fitRange.length)]];

    }


    return textChunks;
}

1 个答案:

答案 0 :(得分:0)

是的,您需要添加段落样式才能使宽度/高度度量正常工作。见giving-framesetter-the-correct-line-spacing-adjustment。请注意CTFontGetLeading()如何用于获取字体前导,然后将此属性设置为vai CFAttributedStringSetAttributes()。