Can't set linkAttributes on TTTAttributedLabel

流过昼夜 提交于 2019-12-25 04:24:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!