TTTAttributedLabel custom addLinkToURL not working

623 views Asked by At

I use an api that returns hyperlinks in format.

I use a regex to get the text between the tags, and the text between the href to get the url. I want to display the text between the tags and link to the url in the href.

I create the label like this:

TTTAttributedLabel * attributedLabel = [[TTTAttributedLabel alloc] init];
[attributedLabel setFont:font];
[attributedLabel setTextColor:[UIColor colorFromHex:0x4b4b4b]];
[attributedLabel setLineBreakMode:NSLineBreakByWordWrapping];
[attributedLabel setNumberOfLines:0];

attributedLabel.userInteractionEnabled = YES;
[attributedLabel setEnabledTextCheckingTypes:NSTextCheckingTypeLink];
[attributedLabel setDelegate:delegate];

attributedLabel.linkAttributes = @{ (id)kCTForegroundColorAttributeName: [UIColor colorFromHex:0x0080be],
                                 (id)kCTUnderlineStyleAttributeName : [NSNumber numberWithInt:NSUnderlineStyleNone] };

[attributedLabel setText:string];

And i set the url and the text like this, i will spare you the regex (the urls are set in a different function, so attributedLabel is now label):

NSString *replacementString = [label.text substringWithRange:[match rangeAtIndex:2]];
NSString *linkString = [label.text substringWithRange:[match rangeAtIndex:1]];
label.text = [label.text stringByReplacingCharactersInRange:[match rangeAtIndex:0] withString:replacementString];
NSRange replacementRange = NSMakeRange([match rangeAtIndex:0].location, [replacementString length]);
[label addLinkToURL:[NSURL URLWithString:linkString] withRange:replacementRange];

Even if i log the [label links] i get the following result:

    (
    "<NSLinkCheckingResult: 0x7b9f2780>{454, 4}  {http://mysuperawesomesite.com}"
)

Does anyone know what i might do wrong?

1

There are 1 answers

0
Jonathan Hersh On

You must use TTTAttributedLabel's designated initializer, initWithFrame:, even if you pass CGRectZero as the frame. You are using init here, which will not initialize the links array and various other internal properties.