我已经编写了这段代码来检测网址...即如果我在textview中键入一个URL,则它应该检测到该URL并显示一条消息。这段代码是用textview shouldChangeTextIn range...
编写的。
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if textView == contributeTextView {
let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let matches = detector.matches(in: textView.text, options: [], range: NSRange(location: 0, length: textView.text.utf16.count))
for match in matches {
guard let range = Range(match.range, in: textView.text) else { continue }
url = textView.text[range]
print("THIS IS THE URL:-> \(url)")
}
return true
}
//CODE TO GET URL AS UNDERLINED
.......
return true
}
此代码运行正常。但是,如果它是一个网址,那么我还希望在该网址下方显示一个下划线,以表明它是一个网址。为此,我编写了以下代码...
//CODE TO GET URL AS UNDERLINED
let attributedString = NSMutableAttributedString(string: textView.text)
let range = (textView.text as NSString).range(of: "\(url)")
attributedString.addAttribute(.link, value: "\(url)", range: range)
textView.attributedText = attributedString
但是它不起作用。出了什么问题...? 另外,如果我写了整个URL并按了空格,那么我在哪里可以知道该空格已被按下...?