我编写了这段代码来检测 url...即如果我在 TextView 中输入一个网址,那么它应该检测到该网址并显示一条消息。这段代码是在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
}
这段代码运行良好。但如果它是一个 url,那么我还希望在该 url 下方显示一条下划线以表明它是一个 url。为此,我编写了以下代码...
//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
但是它不起作用。出了什么问题...? 另外,如果我写下整个网址并按空格,我在哪里可以知道空格已被按下...?
最佳答案
您的代码无法正常工作的原因是 addAttribute
的 value
错误。这是正确的片段。
let attributedString = NSMutableAttributedString(string: textView.text)
let range = (textView.text as NSString).range(of: "\(url)")
attributedString.addAttribute(.link, value: 1, range: range)
attributedString.addAttribute(.underlineStyle, value: 1, range: range)
attributedString.addAttribute(.underlineColor, value: UIColor.blue, range: range)
textView.attributedText = attributedString
关于ios - 无法获取 url 的下划线并检测 url 后的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55390084/