2

我需要点击部分的文本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);
}

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

4

2 回答 2

4

我能想到的唯一解决方案是实施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;
}
于 2016-04-13T11:46:13.493 回答
0

斯威夫特 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)
}
于 2019-02-27T23:04:33.547 回答