mjh
mjh

Reputation: 3508

Coloring links with multiple various colors in the same NSAttributedString

I'm using TTTAttributedLabel to detect clicks on links in a styled UILabel (using NSAttributedString), in an iOS 6 project. I'd like to be able to have alternating colors for links in my label; I'm fine with manually setting the different colors for different link ranges, as long as the library handles link-detection with user touches for me. It seems that the TTTAttributedLabel class applies link styling last, so that text styling for specific ranges is overwritten by the single link style set for the class instance.

Being about to dive in and try to modify the TTTAttributedLabel code (to either not apply link styling, or to apply my own style ranges afterwards), I figured I'd ask here whether anyone has better ideas to consider for achieving this. Might a different library support variously-colored link ranges in the same label, out of the box?

Upvotes: 2

Views: 2391

Answers (1)

mjh
mjh

Reputation: 3508

This is already supported, simply use:

- (void)addLinkWithTextCheckingResult:(NSTextCheckingResult *)result
                           attributes:(NSDictionary *)attributes;

This lets you specify your own attributes on a per-link basis. E.g., with a linkAttributes dictionary for one-off coloring of a link:

if (linkAttributes) {
    [self addLinkWithTextCheckingResult:[NSTextCheckingResult linkCheckingResultWithRange:linkRange URL:[NSURL URLWithString:linkText]] attributes:linkAttributes];
}
else {
    [self addLinkToURL:[NSURL URLWithString:linkText] withRange:linkRange];
}

The link attributes dictionary uses keys defined in NSAttributedString.h. For example:

linkAttributes = @{
    NSForegroundColorAttributeName: [UIColor greenColor],
    NSUnderlineStyleAttributeName: @(NSUnderlineStyleNone)
};

Upvotes: 5

Related Questions