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

Manually formatting url starting with http or https in string for UITextView of iOS/Xcode

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

例如,从"www.google.com and https://www.gogole.com and http://www.google.com as well as "google.com"开始,我只想将url以https或http开头的文本变成蓝色下划线文本,并保持在同一个原始句子中,如果不是在新句子中修改了 selected urls。 这种方法有可能吗?或者我可以用哪种方式实现它?

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

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"{
}