iOS设置UITextView文字链接

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]
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容