无法在TTTAttributedLabel上设置linkAttributes [英] Can't set linkAttributes on TTTAttributedLabel
问题描述
使用TTTAttributedLabel和我的代码:
Using TTTAttributedLabel, with my code:
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];
就轻敲范围文本并执行操作而言,一切都可以完美地工作,但是,唯一看起来不起作用的是文本颜色.我在lib中正确使用了NSForegroundColorAttributeName
吗?
Everything works perfectly, in terms of tapping the range text and performing an action, however, the only thing that doesn't seem to work is the text colour. Am I using NSForegroundColorAttributeName
correctly with the lib?
不起作用"是,带下划线的文字保持灰色,而不是像我上面设置的那样红色.
By, "doesn't work", is that the underlined text stays grey, and not red like I've set it above.
推荐答案
我遇到了同样的问题,经过了一段时间的努力,但仍然没有找到原因,我退出了您提到的解决方案,并提出了解决方案以下方法:
I encounter the same problem before, after struggled for quite some time and still did not find out the reason, I drop out of your mentioned solution and come up with the following method:
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
}
此解决方案的优点是您可以根据需要添加任意数量的自定义链接样式.
The advantage of this solution is you can add as many customised link style as you wish.
当然,如果您坚持使用addLinkToURL
,则另一种可能的解决方案是更改TTTAttributedLabel
源代码以更改默认链接颜色.
Of course another possible solution if you insist using addLinkToURL
is to change TTTAttributedLabel
source code to change the default link color.
这篇关于无法在TTTAttributedLabel上设置linkAttributes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!