0

使用 TTTAttributedLabel 和我的代码:

NSString *contentText = @"some text here foo bar";

[self.content setText:contentText afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
    return mutableAttributedString;
}];
self.content.linkAttributes = @{ NSForegroundColorAttributeName: [UIColor redColor],
                               NSUnderlineStyleAttributeName: [NSNumber numberWithInt:NSUnderlineStyleSingle] };
NSRange range = [self.content.text rangeOfString:@"foo bar"];
[self.content addLinkToURL:[NSURL URLWithString:@"action://load-foo"] withRange:range];
[self.content setNeedsDisplay];

在点击范围文本和执行操作方面,一切都完美无缺,但是,唯一似乎不起作用的是文本颜色。我NSForegroundColorAttributeName是否正确使用了库?

编辑:

“不起作用”是带下划线的文本保持灰色,而不是像我在上面设置的那样是红色的。

4

1 回答 1

1

我之前也遇到过同样的问题,挣扎了好久还是没找到原因,放弃了你说的解决方法,想出了如下方法:

NSString *contentText = @"some text here foo bar";
NSString* matchString = @"foo bar";
NSRegularExpression *mentionExpression = [NSRegularExpression regularExpressionWithPattern:matchString options:NO error:nil];
NSArray *matches = [mentionExpression matchesInString:contentText
                                                  options:0
                                                    range:NSMakeRange(0, [contentText length])];
    for (NSTextCheckingResult *match in matches) {
        NSRange matchRange = [match rangeAtIndex:0];
        NSString *mentionString = [contentText substringWithRange:matchRange];
        NSArray *keys = @[(id) kCTForegroundColorAttributeName, (id) kCTUnderlineStyleAttributeName
        ];
        NSArray *objects = @[[UIColor redColor], @(kCTUnderlineStyleNone)];
        NSDictionary *linkAttributes = @{keys : objects};

        [self.yourlabel addLinkWithTextCheckingResult:match attributes:linkAttributes];
    }
    self.yourlabel.delegate = self;

//Then overwrite the delegate method for the link click actions
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithTextCheckingResult:(NSTextCheckingResult *)result {
    //do whatever you need
}

此解决方案的优点是您可以根据需要添加任意数量的自定义链接样式。

当然,如果您坚持使用另一种可能的解决方案addLinkToURL是更改TTTAttributedLabel源代码以更改默认链接颜色。

于 2015-01-27T09:46:56.227 回答