iOS5対応のアプリを作る時に困るのは、NSStringやUILabelを使って文字列を出力する時に、途中で、色をかえたり、リンクを追加するのが非常にめんどいということ。
CoreTextを使えばできるのだが、めんどいのでオープンソースでカバーできないかなーっと思っていたら、
TTTAttributedLabel
という素敵なコードがあったので、適用方法を勉強することに。
基本的には、githubのソースを見ればいいのだが、下のような感じで使うことができる。
CGRect rect;
TTTAttributedLabel *tTTAttributedLabel = [[TTTAttributedLabel alloc] initWithFrame:rect];
tTTAttributedLabel.backgroundColor = [UIColor clearColor];
tTTAttributedLabel.font = [UIFont systemFontOfSize:10];
tTTAttributedLabel.lineBreakMode = UILineBreakModeTailTruncation;
tTTAttributedLabel.textColor = [UIColor redColor];
tTTAttributedLabel.textAlignment = UITextAlignmentLeft;
tTTAttributedLabel.numberOfLines = 0;
UIColor *fontColor;
出力したい文字列
NSString *newDispComment;
[tTTAttributedLabel setText:newDispComment afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
//途中で色を変更する
NSUInteger toIdx;
NSRange colorChangeRange = [[mutableAttributedString string] rangeOfString:username options:NSCaseInsensitiveSearch range:NSMakeRange(0, toIdx)];
[mutableAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName value:(id)[fontColor CGColor] range:colorChangeRange];
return mutableAttributedString;
}]; こんな風に実装すれば、文字列の途中で色を変更することは可能です。ARCでコンパイルできるので、当然、iOS5以降にも対応しています。
めちゃ便利。
0 コメント:
コメントを投稿