【发布时间】:2014-03-10 22:41:14
【问题描述】:
我已向 TTTAttributedLabel 添加了一个链接检测器,用于识别 @mentions 和 #hashtags 并在我的 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;
但这会改变每个链接属性的颜色 - 包括网络链接、主题标签和提及。有没有办法使用正则表达式或范围创建不同的链接颜色?假设我希望@mentions 为灰色,@hashtags 为红色,网络链接为蓝色?
【问题讨论】:
-
更简单的解决方案是:self.attributedLabel.linkAttributes = @{ NSForegroundColorAttributeName: [UIColor darkGrayColor], NSUnderlineStyleAttributeName:[NSNumber numberWithInt:NSUnderlineStyleSingle]}; NSRange r1 = [labelText rangeOfString:@"隐私政策"]; [self.attributedLabel addLinkToURL:[NSURL URLWithString:@"action://PrivacyPolicy"] withRange:r1];
标签: ios objective-c tttattributedlabel