@mentions と #hashtags を識別し、私の TTTAttributedLabel インスタンスのその位置にリンクを作成するリンク検出器を TTTAttributedLabel に追加しました。
- (void)highlightMentionsInString:(NSString *)text withColor:(UIColor *)color isBold:(BOOL)bold isUnderlined:(BOOL)underlined
{
NSRegularExpression *mentionExpression = [NSRegularExpression regularExpressionWithPattern:@"(?:^|\\s)(@\\w+)" options:NO error:nil];
NSArray *matches = [mentionExpression matchesInString:text
options:0
range:NSMakeRange(0, [text length])];
for (NSTextCheckingResult *match in matches) {
NSRange matchRange = [match rangeAtIndex:1];
NSString *mentionString = [text substringWithRange:matchRange];
NSRange linkRange = [text rangeOfString:mentionString];
NSString* user = [mentionString substringFromIndex:1];
NSString* linkURLString = [NSString stringWithFormat:@"user:%@", user];
[self.attributedLabel addLinkToURL:[NSURL URLWithString:linkURLString] withRange:linkRange];
}
}
また、リンクの色と属性を簡単に変更するためにこれを行うことができることも発見しました。
NSArray *keys = [[NSArray alloc] initWithObjects:(id)kCTForegroundColorAttributeName,(id)kCTUnderlineStyleAttributeName
, nil];
NSArray *objects = [[NSArray alloc] initWithObjects:color,[NSNumber numberWithInt:kCTUnderlineStyleNone], nil];
NSDictionary *linkAttributes = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
self.attributedLabel.linkAttributes = linkAttributes;
ただし、これにより、Web リンク、ハッシュタグ、メンションなど、すべてのリンク属性の色が変更されます。正規表現または範囲を使用して異なるリンクの色を作成する方法はありますか? @メンションをグレー、@ハッシュタグを赤、Web リンクを青にしたいとします。