在 TTTAttributedLabel 中获取点击 URL 的文本部分

Get text part of clicked URL in TTTAttributedLabel

我需要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);
}

但我只有 link 和整个标签,但没有被点击的部分(被点击的文本部分)。我怎样才能得到它?

我能想到的唯一解决方案是实施 attributedLabel: didSelectLinkWithTextCheckingResult: 而不是 attributedLabel: didSelectLinkWithURL:

它的好处是 NSTextCheckingResult 包含一个 范围 属性,您可以使用它来查找实际文本(而不是 URL ) 点击了。

- (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;
}

Swift 4 片段

func attributedLabel(_ label: TTTAttributedLabel!, didSelectLinkWith result: NSTextCheckingResult!) {
    guard let checkingResult = result else { return }
    guard let clickedURL = checkingResult.url else { return }
    guard let text = label.text as? NSString else { return }

    let clickedText = text.substring(with: checkingResult.range)
}