ios 如何在NSAttributedString中查找网址?[duplicate]

thtygnil  于 2023-02-14  发布在  iOS
关注(0)|答案(1)|浏览(112)
    • 此问题在此处已有答案**:

Detect UIWebView links without click(2个答案)
十小时前关门了。
我有一个简单的属性化字符串:

let string = NSAttributedString(string: "hello https://www.stackoverflow.com")

当我显示该字符串时,我希望看到:

hello URL

其中URL是可点击链接,可打开https://www.stackoverflow.com
链接不是硬编码的,在我替换它的时候,我不知道有多少(如果有的话)链接存在。

    • 编辑:**

看这道题,和标为重复的那道题比较一下。它不是重复的。请明智聪明地复习。

vsnjm48y

vsnjm48y1#

这应该可以达到目的:

let linkDetector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let str = "hello at https://www.stackoverflow.com or http://google.com ?"

let attrStr = NSMutableAttributedString(string: str)

let matches = linkDetector.matches(in: attrStr.string, range: NSRange(location: 0, length: attrStr.string.utf16.count))

matches.reversed().forEach { aMatch in //Use `reversed()` to avoid range issues
    let linkRange = aMatch.range
    let link = (attrStr.string as NSString).substring(with: linkRange) //Or use Range
    //Here, you could modify the "link", and compute if needed myURLTitle, like URL(string: link)?.host ?? "myURLTitle"
    let replacement = NSAttributedString(string: "myURLTitle", attributes: [.link: link])
    attrStr.replaceCharacters(in: linkRange, with: replacement)
}

print(attrStr)

相关问题