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
    }

效果图

相关推荐
茶底世界之下9 小时前
灯塔照片怎么裁竖幅?用 Awaking 留住塔顶,收紧两侧环境
ios
朝阳58111 小时前
Mac 上找窗口,可以先按这几种情况来
macos
庚鑫12 小时前
iOS 27 兼容放大模式下,keyboardFrame 与 UIScreen.bounds 的坐标差异
ios·objective-c
william_yangshun12 小时前
DigUp 实测:用多模态嵌入做 macOS 全盘语义搜索
macos·向量检索
czt_java13 小时前
网络基础入门:IPv4、IPv6、私网公网、MAC、以太网帧与 DNS 学习笔记
网络·学习·macos
HEJOO913 小时前
iOS 高效绘图:从 Core Graphics 到 Metal 的实践指南
macos·ios·cocoa
Hello_Pyhx14 小时前
RetainPDF v4.2.6:Windows、macOS、Linux PDF 翻译的 API 配置与任务排查
linux·macos·pdf
HEJOO914 小时前
iOS 性能优化全面详解
ios·性能优化·cocoa
ii_best14 小时前
iOS 自动化脚本工具更新|按键精灵 适配 Relaxin(青霉素)越狱,兼容 iOS16~iOS26 主流越狱环境
ios·自动化·按键精灵
万年咸鱼14 小时前
iOS 27 适配笔记
笔记·ios·cocoa