ios - 匹配字符串中的<a> anchor 标记,提取其 `href`

标签 ios swift

我试图将字符串中的所有标签链接到各自的 href,以便可以在浏览器中点击并打开它。

这就是我所拥有的,

<p>This is a simple text with some embedded <a href="http://example.com/link/to/some/page?param1=77&param2=22">links</a>. 
This is a <a href="https://exmp.le/sample-page/?uu=1">different link</a>.

如何处理此文本并将所有 anchor 标记链接到各自的 href?

我想要实现的伪代码:

let finalContentLabel = TTTAttributedLabel(frame: CGRect.zero)
for (linkText, linkHref) in paragraph.anchorTags() {
    let range:NSRange = (finalContentLabel.text as! NSString).range(of: linkText)
    finalContentLabel.addLink(to: URL(string: linkHref), with: range)
}

我已经弄清楚了除了 paragraph.anchorTags() 位之外的所有内容。

最佳答案

您可以使用标准标签和从 HTML 创建的属性字符串,然后您的标签中将包含链接

let label = UILabel()
let attributedText = try? NSAttributedString(data: <your string>.data(using: .utf8)!, options: 
            [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, 
            NSCharacterEncodingDocumentAttribute: String.Encoding.utf8 ], 
            documentAttributes: nil)

//接下来将是 OBJC

NSMutableAttributedString *mutableText = [[NSMutableAttributedString alloc] initWithAttributedString:attributedText];

self.textContainer = [[NSTextContainer alloc] initWithSize:self.label.bounds.size];
self.textContainer.lineFragmentPadding = 0;
self.textContainer.maximumNumberOfLines = self.label.numberOfLines;
self.textContainer.lineBreakMode = self.label.lineBreakMode;
self.layoutManager = [NSLayoutManager new];
[self.layoutManager addTextContainer:self.textContainer];
self.textStorage = [[NSTextStorage alloc] initWithAttributedString:self.label.attributedText];
[self.textStorage addLayoutManager:self.layoutManager];

在属性字符串中,带有链接的文本范围将具有属性NSLinkAttributeName。您可以对该属性进行enumerateAttribute,并为该属性的每个范围添加您自己的字体和颜色,从该范围中删除该NSLinkAttributeName,然后添加MYLinkAttributeName > 属性代替。

[attributedText enumerateAttribute:NSLinkAttributeName inRange:NSMakeRange(0, attributedText.length) options:kNilOptions usingBlock:^(id  _Nullable value, NSRange range, BOOL * _Nonnull stop) {
            if (nil != value)
            {
                [mutableText addAttribute:NSStrokeColorAttributeName value:greenColor range:range];
                [mutableText addAttribute:NSForegroundColorAttributeName value:greenColor range:range];
                [mutableText addAttribute:MYLinkAttributeName value:value range:range];
                [mutableText removeAttribute:NSLinkAttributeName range:range];
            }
        }];

然后,在标签上添加 UITapGestureRecognizer 并实现其 delegate 回调

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    self.textContainer.size = self.label.bounds.size;
    NSUInteger index = [self.layoutManager characterIndexForPoint:[touch locationInView:self.label]
                                             inTextContainer:self.textContainer
                    fractionOfDistanceBetweenInsertionPoints:NULL];
    self.lastTouchedLinkAttributeValue = [self.label.attributedText attribute:MYLinkAttributeName atIndex:index effectiveRange:NULL];

    return nil != self.lastTouchedLinkAttributeValue;
}

最后,识别器操作:

- (IBAction)tapRegognized:(id)sender
{
    // Here value of 'href' is stored in self.lastTouchedLinkAttributeValue as NSURL instance.
}

关于ios - 匹配字符串中的<a> anchor 标记,提取其 `href`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43813922/

相关文章:

ios - 滚动 Swift 时 tableView 的值重复

objective-c - 在异步 HTTP 请求的 completionHandler 中更新 View 时出现延迟

ios - 双击后退按钮 UINavigationBar 时弹出到 root

ios - 是否可以通过单击应用程序的 WebView 中的 URL 打开移动 safari?

ios - 在 appdelegate 中设置 UIButton 的外观 - setClipsToBounds

ios - 与数组一起使用的字典键值

ios - CloudKit 问题 : did not find required record type

ios - 如何创建一个 UIButton 调整大小以适应其中的图像?

swift - 使 Optional.none 评估为 0

swift - react swift : How to observe UIView isHidden?