Search code examples
iosobjective-ctttattributedlabel

Get text part of clicked URL in TTTAttributedLabel


I need the text of clicked part of TTTAttributedLabel:

// initialize
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ...

    // Attributed Message Label
    NSMutableAttributedString *messageTextAttr =[row valueForKey:@"message_text_attr"];

    cell.messageText.attributedText = messageTextAttr;
    cell.messageText.delegate = self;

    [messageTextAttr enumerateAttribute:NSLinkAttributeName inRange:NSMakeRange(0, messageTextAttr.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
        if (value) {
            [cell.messageText addLinkToURL:[NSURL URLWithString:value] withRange:range];
        }
    }];

    ...
}

// click event
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    NSLog(@"link %@", [url absoluteString]);
    NSLog(@"whole label %@", label);
}

But I have only the link and whole label, but not the clicked part (text part which is clicked). How can I get it?


Solution

  • The only solution I can think of is implementing attributedLabel: didSelectLinkWithTextCheckingResult: instead of attributedLabel: didSelectLinkWithURL:.

    It's benefit is that the NSTextCheckingResult contains a range property that you can use to find the actual text (not the URL) clicked.

    - (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithTextCheckingResult:(NSTextCheckingResult *)result {
    
        NSString* textClicked = [label.text substringWithRange:result.range];
    
        //Get the URL and perform further actions
        NSURL* urlClicked = result.URL;
    }