func configService() {
let str = "我已阅读并同意《用户服务协议》和《隐私政策》"
let str1 = "《用户服务协议》"
let str2 = "《隐私政策》"
let range1 = (str as NSString).range(of: str1)
let range2 = (str as NSString).range(of: str2)
let font = UIFont.systemFont(ofSize: 12)
let color = colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
let color1 = colorLiteral(red: 0.8352941176, green: 0.06274509804, blue: 0.0431372549, alpha: 1)
let att: [NSAttributedStringKey: Any] = [
.foregroundColor: color,
.font: font
]
let att1: [NSAttributedStringKey: Any] = [
.link: "service://",
.font: font,
.foregroundColor: color1
]
let att2: [NSAttributedStringKey: Any] = [
.link: "privacy://",
.font: font,
.foregroundColor: color1
]
let attStr = NSMutableAttributedString.init(string: str, attributes: att)
attStr.addAttributes(att1, range: range1)
attStr.addAttributes(att2, range: range2)
textView.attributedText = attStr
textView.delegate = self
// 消除超链接原有的字体颜色,此处如不设置,设置的att1颜色可能不会生效
textView.linkTextAttributes = [:]
// 此处必须设置为true,否则点击事件会不生效
textView.isSelectable = true
// 此处必须设置为false
textView.isEditable = false
}
// UITextViewDelegate
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
if URL.scheme == "service" {
print("service点击事件")
} else if URL.scheme == "privacy" {
print("privacy点击事件")
}
return true
}