做项目时用了UITextView加链接的方式,做文本的点击事件
let ruleStr = "I have read and accepted privacy policy and service agreement"
ruleAttr.addAttribute(NSAttributedString.Key.link, value: "privacy://", range: NSRange(location: 25, length: 14))
ruleAttr.addAttribute(NSAttributedString.Key.link, value: "sagreement://", range: NSRange(location: 44, length: 17))
self.privacyAgreementTV.delegate = self
self.privacyAgreementTV.isEditable = true self.privacyAgreementTV.isScrollEnabled = false
self.privacyAgreementTV.attributedText = ruleAttr
self.privacyAgreementTV.font = UIFont.systemFont(ofSize: 12)
self.privacyAgreementTV.linkTextAttributes = [.foregroundColor:main_color]
extension MyController: UITextViewDelegate {
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
if URL.scheme == "privacy" {
KYTool.ky_showText(textStr: "123")
}else if URL.scheme == "sagreement" {
KYTool.ky_showText(textStr: "456")
}
return true
}
}
到此,基本功能大致完成,如果有想改进的自行查阅其他内容
重点是:长按事件屏蔽,遍历了一下UITextView的事件,高达20多种,突发奇想,手动删除不要的事件,如下
//遍历所有手势,留下点击的手势
for ges in privacyAgreementTV.gestureRecognizers! {
if !(ges is UITapGestureRecognizer) { //如果不是单击手势,全部删除
privacyAgreementTV.removeGestureRecognizer(ges)
}
}
齐活!!!