Способ сделать это:
Используйте 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"{
}