iOS textView支持超链接跳转

将某些文字变成高量可以点击的超链接核心功能代码

复制代码
        attri.addAttribute(NSAttributedString.Key.link, value:NSURL.init(string: "dctt:p/userPrivacy.html")!, range: NSRange.init(location: s.count - 4, length: 4) )

        textView.linkTextAttributes = [NSAttributedString.Key.foregroundColor:UIColorFromHex(rgbValue: 0xff4500) ]

同时,要实现点击超链接的UITextView代理方法

复制代码
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction API_AVAILABLE(ios(10.0));

完整代码

复制代码
   let s = "本《隐私概要》将向你说明:\n1.为了帮助你浏览、发布信息、评论交流、注册认证,我们会收集你的部分必要信息;\n\n2.为了提供以上服务,我们可能会收集联络方式、位置、通讯录等部分敏感信息,你有权拒绝或撤销授权;\n\n3.未经你同意,我们不会从第三方获取、共享或提取你的信息;\n\n4.你可以访问、更正、删除你的个人信息,我们也将提供注销、投诉的方式。如果你点击不同意,我们将仅收集浏览内容所必须的信息,但发布信息、交流评论可能会受到影响。\n\n前往查看完整的 隐私政策"
        
        let attri = NSMutableAttributedString.init(string: s)
        
//        attri.addAttributes([NSForegroundColorAttributeName:UIColor.red ], range: NSRange.init(location: s.count - 4, length: 4))
        
        attri.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 15), range: NSRange.init(location: 0, length: s.count))
        
        attri.addAttribute(NSAttributedString.Key.link, value:NSURL.init(string: "dctt:p/userPrivacy.html")!, range: NSRange.init(location: s.count - 4, length: 4) )
        
        textView.linkTextAttributes = [NSAttributedString.Key.foregroundColor:UIColorFromHex(rgbValue: 0xff4500) ]
        
        textView.attributedText = attri;
        textView.delegate = self

实现代理方法

复制代码
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {        
        if let scheme = URL.scheme , scheme == "dctt" {
            let vc = BaseWebViewController(baseUrl:privacy_agreement_url)
            vc.title = "隐私政策"

            self.navigationController?.pushViewController(vc, animated: true)
            return false
        }
        
        return true
    }

效果图

相关推荐
人月神话Lee44 分钟前
【图像处理】vImage/Accelerate——SIMD 让 CPU 也能飞
ios·swift·图像识别
cmdyu_3 小时前
mac上如何卸载node.js
macos·node.js
2601_955767424 小时前
iPhone 17 护眼钢化膜怎么选?从PWM频闪到圆偏振光,解析「软硬协同」光学方案
ios·ar·iphone·护眼钢化膜·圆偏振光·#观复盾护景贴·磁控溅射
黑化旺仔5 小时前
【OC】PHPickerViewController
macos·objective-c·cocoa
AI行业学习6 小时前
CC-Switch 下载、安装windows\macOS \Linux 安装
linux·运维·macos
2601_955767427 小时前
iPhone 17 护眼保护膜怎么选?圆偏振光 + AR 抗眩方案,解读 96% 透光率与 ≤0.5% 反射率的协同价值
ios·ar·iphone·圆偏振光·#观复盾护景贴·scinique双护技术
三雒7 小时前
KMP 实战:Android 开发如何快速统一双端 IM 模块
android·ios·kotlin
一个人旅程~8 小时前
完整精华版macbookHighSierra 至Montere-Ventyra版本跨越评估与避坑指南(含证书有效期)
windows·经验分享·macos·电脑
秋雨梧桐叶落莳8 小时前
iOS——抽屉视图详解
开发语言·macos·ui·ios·objective-c·cocoa
库奇噜啦呼9 小时前
【iOS】源码学习-方法交换
学习·ios·cocoa