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
    }

效果图

相关推荐
dnekmihfbnmv5 小时前
好用的电容笔有哪些推荐一下?年度最值得推荐五款电容笔分享!
ios·电脑·ipad·平板
黑果魏叔5 小时前
macOS Sequoia 正式版(24A335)黑苹果/Mac/虚拟机系统镜像
macos
tekin6 小时前
macos macport软件包管理工具 sudo port install xxx 安装的软件的路径 与 brew install xxx 软件安装路径总结
macos·brew·port·macport·port install·port软件包安装路径·brew软件包安装路径
Hellc0078 小时前
MacOS升级ruby版本
前端·macos·ruby
GEEKVIP15 小时前
Android 恢复挑战和解决方案:如何从 Android 设备恢复删除的文件
android·笔记·安全·macos·智能手机·电脑·笔记本电脑
逢生博客20 小时前
Mac 搭建仓颉语言开发环境(Cangjie SDK)
macos·华为·鸿蒙
Rverdoser1 天前
MacOS Catalina 从源码构建Qt6.2开发库之01: 编译Qt6.2源代码
macos
Magnetic_h1 天前
【iOS】单例模式
笔记·学习·ui·ios·单例模式·objective-c
归辞...1 天前
「iOS」——单例模式
ios·单例模式·cocoa
GEEKVIP1 天前
如何在没有备份的情况下恢复 Mac 上丢失的数据
经验分享·笔记·安全·macos·电脑·笔记本电脑·改行学it