gpt4 book ai didi

ios - 为 iOS/Xcode 的 UITextView 手动格式化字符串中以 http 或 https 开头的 url

转载 作者:行者123 更新时间:2023-11-28 05:57:33 25 4
gpt4 key购买 nike

我想从字符串中选择一堆仅以 http 或 https 开头的 url。在 UITextView 中,可以将 .dataDetectorTypes 设置为 .link 以将所有 url 变成蓝色下划线文本。

例如,从 "www.google.com and https://www.gogole.com and http://www.google.com as well as "google.com" 我会喜欢只将以 https 或 http 开头的 url 转换为带蓝色下划线的文本,并将它们保留在同一个原始句子中,如果不是在具有修改后的选定 url 的新句子中。这种方法有可能吗?或者我可以用哪种方式实现它。?

最佳答案

一种方法:
使用 NSMutableAttributedString
使用 NSDataDetector 查找所有链接。
枚举 (enumerateMatches(in:options:range:using:)) 并根据您的规则编辑是否要添加或不添加 NSAttributedStringKey.link

let initialString = "www.google.com and https://www.gogole.com and http://www.google.com as well as \"google.com\""
let linkDetector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)

let attributedString = NSMutableAttributedString(string: initialString)

linkDetector.enumerateMatches(in: attributedString.string,
options: [],
range: NSRange(location: 0, length: attributedString.string.utf16.count)) { (match, flags, stop) in
if let match = match, match.resultType == NSTextCheckingResult.CheckingType.link, let url = match.url {
if let range = Range(match.range, in: attributedString.string) {
let substring = attributedString.string[range]
if substring.hasPrefix("http") {
attributedString.addAttribute(.link, value: url, range: match.range)
}
}
}
}

我使用了测试 substring.hasPrefix("http"),但你可以使用你想要的那个。

输出:

attributedString:
www.google.com and {
}https://www.gogole.com{
NSLink = "https://www.gogole.com";
} and {
}http://www.google.com{
NSLink = "http://www.google.com";
} as well as "google.com"{
}

关于ios - 为 iOS/Xcode 的 UITextView 手动格式化字符串中以 http 或 https 开头的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51019708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com