TTTAttributedLabelをつかってみた!

matttさんが作成されたObjective-Cのライブラリ、TTTAttributedLabelを使ってみました。

どんなもの?

NSAttributedStringを使って書式の混在したUILabelを作成できるライブラリです。
太字・斜体だけじゃなく、文中にリンクの設定もできちゃいます。すごい!
対象OSは3.2〜。
わたしはTableViewCellのLabelをカスタムするのに使いました。

つかいかた

ほぼREADME.mdそのままですが、使いかたはこんな感じ。
setTextの引数に、Labelに表示したい文(すべて)を、装飾したい文字はブロックの中でNSRangeとして指定。
IBは使えないので、適宜プロパティをセットして使います。

太字+ふつうの文字を生成:

TTTAttributedLabel* label = [[[TTTAttributedLabel alloc] initWithFrame:CGRectZero] autorelease];
[label setFont:[UIFont systemFontOfSize:[UIFont systemFontSize]]];

[label setText:@"I like cats." afterInheritingLabelAttributesAndConfiguringWithBlock:^ (NSMutableAttributedString *mutableAttributedString) {
    
    NSRange boldRange = [[mutableAttributedString string] rangeOfString:@"cats" options:NSCaseInsensitiveSearch];
    
    UIFont *boldSystemFont = [UIFont boldSystemFontOfSize:[UIFont systemFontSize]]; 
    
    CTFontRef font = CTFontCreateWithName((CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);

    if (font) {
        [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(id)font range:boldRange];
        CFRelease(font);
    }
    
    return mutableAttributedString;
}];