【问题标题】:Get text part of clicked URL in TTTAttributedLabel在 TTTAttributedLabel 中获取点击的 URL 的文本部分
【发布时间】:2016-04-13 10:31:54
【问题描述】:

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

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

【问题讨论】:

  • URL 是您按下的链接,您是否为 @ 、 # 之类的内容添加自定义链接属性?
  • @SeanLintern88 不,我需要点击标签的文本部分,而不是整个文本。
  • 是的,URL 是用户点击的文本。 url.absoluteString()?
  • 每个链接有两部分:URL和文本,我需要文本
  • 你能添加你如何初始化 TTTAttributedLabel 的代码吗?

标签: ios objective-c tttattributedlabel


【解决方案1】:

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

它的好处是NSTextCheckingResult 包含一个 range 属性,您可以使用该属性来查找实际点击的文本(而不是 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;
}

【讨论】:

    【解决方案2】:

    Swift 4 sn-p

    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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-08
      • 2014-04-16
      • 1970-01-01
      • 2021-07-06
      • 2013-06-15
      相关资源
      最近更新 更多