setting up attributes for links in NIAttributedLabel

401 Views Asked by At

I have done the following to have different color for links in my NIAttributedLabel:

NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        [attributes setValue:[UIColor colorWithRed:86.0/255.0 green:134.0/255.0 blue:172.0/255.0 alpha:1.0] forKey:NSForegroundColorAttributeName];
        [attributes setValue:[UIColor colorWithRed:0.0 green:136/255.f blue:204/255.f alpha:1.0] forKey:NSForegroundColorAttributeName];
        [self.commentsText_ setAttributesForLinks:attributes];

but I am not seeing two different colors in the links, instead I am just seeing one. What am I doing wrong here? Basically I have a link that I've added via addLink as follows:

[self.commentsText_ addLink:[NSURL URLWithString:url] range:usernameRange];

and I want this to have the redColor. How do I do so?

2

There are 2 best solutions below

2
On

If you want different colors for different links, then you need to create separate attribute dictionaries, and call setAttributesForLinks: with the different dictionaries.

        NSMutableDictionary *attributes1 = [NSMutableDictionary dictionary];
        [attributes setValue:[UIColor colorWithRed:86.0/255.0 green:134.0/255.0 blue:172.0/255.0 alpha:1.0] forKey:NSForegroundColorAttributeName];  
        [self.commentsText1_ setAttributesForLinks:attributes1];

        NSMutableDictionary *attributes2 = [NSMutableDictionary dictionary];
        [attributes setValue:[UIColor colorWithRed:0.0 green:136/255.f blue:204/255.f alpha:1.0] forKey:NSForegroundColorAttributeName];  
        [self.commentsText2_ setAttributesForLinks:attributes2];
0
On

If you would like to set different colors for different links then you should disable the automatic link styles by setting linkColor to nil and then explicitly apply the different styles to your links.