在TTTAttributedLabel中指定多个/条件链接颜色

我添加了TTTAttributedLabel链接检测器,它标识@mentions和#hashtags,并在TTTAttributedLabel实例中的该位置创build一个链接:

- (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; 

但是这会改变每个链接属性的颜色 – 包括网页链接,主题标签和提及。 有没有办法使用正则expression式或范围创build不同的链接颜色? 说如果我想@条是灰色的,@标签是红色的,网页链接是蓝色的?

我只是在处理类似的问题,遇到了你的问题。 我不知道如何注入某种不同的expression式来匹配我的标签中的其他types的东西,所以你的第一个代码清除了。

对于你的问题,但我所做的是将TTTAttributedLabel方法更改为添加NSTextCheckingResult。 因此,如果我在该方法中for循环进行了一些更改,并使用[self.label addLinkWithTextCheckingResult: attributes: ]并按照您的build议设置属性,则现在该循环如下所示:

 for (NSTextCheckingResult *match in matches) { NSRange matchRange = [match rangeAtIndex:1]; NSString *mentionString = [text substringWithRange:matchRange]; NSString* user = [mentionString substringFromIndex:1]; NSString* linkURLString = [NSString stringWithFormat:@"user:%@", user]; 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.label addLinkWithTextCheckingResult:match attributes:linkAttributes]; } 

在我的情况下,这将显示#和@烤橙。

然后我有- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithTextCheckingResult:(NSTextCheckingResult *)result- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithTextCheckingResult:(NSTextCheckingResult *)result TTTAttributedLabelDelegate方法。 当用户点击#或@文本时,会被NSTextCheckingResult调用。

这是你在找什么?

由于关于链接突出状态的问题还没有得到解答,这里是简单的解决scheme:

 var attrs = [NSFontAttributeName : UIFont.systemFontOfSize(14.0), NSForegroundColorAttributeName: UIColor.blackColor()] label.activeLinkAttributes = attrs