0

非常に長いテキストがあるため、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;
}
4

1 に答える 1

0

はい、幅/高さの測定を適切に機能させるには、段落スタイルを追加する必要があります。give-framesetter-the-correct-line-spacing-adjustment を参照してください。CTFontGetLeading() を使用してフォントの行送りを取得し、このプロパティを CFAttributedStringSetAttributes() で設定する方法に注意してください。

于 2013-06-29T03:01:58.483 に答える