2013/07/19

[iOS][Objective-C]TTTAttributedLabelのリンクの設定

前回、TTTAttributedLabelの適用方法を書きましたが、今回はリンクの設定について

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;
}];

tTTAttributedLabel.delegate = self;
                                
//リンクの設定
NSString moveToURL;
NSUInteger toIdx;
[tTTAttributedLabel addLinkToURL:[NSURL URLWithString:moveToURL] withRange:NSMakeRange(0,toIdx)];
こうすることによって、ある特定の位置をタッチした場合のリンク処理を追加することができて、実際にタッチした場合は、delegateメソッドの- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)urlが呼ばれるので、そこで処理を実行すればいい。

ちなみに、リンク線をなくす場合は、
NSMutableDictionary *mutableLinkAttributes = [NSMutableDictionary dictionary];
[mutableLinkAttributes setValue:[NSNumber numberWithBool:NO] forKey:(NSString *)kCTUnderlineStyleAttributeName];
tTTAttributedLabel.linkAttributes = mutableLinkAttributes;
で実現することができる。リンクの色を変更したい場合は、
//リンクの色
NSMutableDictionary *mutableActiveLinkAttributes = [NSMutableDictionary dictionary];
 [mutableActiveLinkAttributes setValue:(id)[fontColor CGColor] forKey:(NSString *)kCTForegroundColorAttributeName];
tTTAttributedLabel.activeLinkAttributes = mutableActiveLinkAttributes;
で変更することができます。

無茶苦茶便利です。

0 コメント:

コメントを投稿