问题
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];
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?
EDIT:
By, "doesn't work", is that the underlined text stays grey, and not red like I've set it above.
回答1:
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.
Of course another possible solution if you insist using addLinkToURL
is to change TTTAttributedLabel
source code to change the default link color.
来源:https://stackoverflow.com/questions/28166812/cant-set-linkattributes-on-tttattributedlabel