iOS设置UITextView文字链接

2023-05-29  本文已影响0人  Mr_Jee
iOS中给UITextView设置文字链接
let text = "跳转到百度https://www.baidu.com"
let attrs = NSAttributedString(string: text, attributes: [.foregroundColor: UIColor.black, .font: UIFont.systemFont(ofSize: 18)])
let linkValue = "baidu://"
let range = (text as NSString).range(of: "https://www.baidu.com")
attrs.addAttribute(.link, value: linkValue, range: range)
textView.attributedText = attrs

// UITextViewDelegate
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    if URL.scheme?.contains("baidu") == true {
        // 跳转链接

        return false
    }
    return true
}

给链接设置颜色

attrs.addAttribute(.foregroundColor, value: UIColor.red, range: range)

这种设置颜色的方法是无效的;
正确的方法应该是:

textView.linkTextAttributes = [.foregroundColor: UIColor.red]
上一篇下一篇

猜你喜欢

热点阅读