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
    }

效果图

相关推荐
胖虎14 小时前
iOS 应用网络权限弹窗的问题及解决方案
ios·网络请求·权限弹窗
孚亭4 小时前
Swift添加字体到项目中
开发语言·ios·swift
2501_915909065 小时前
WebView 调试工具全解析,解决“看不见的移动端问题”
android·ios·小程序·https·uni-app·iphone·webview
2501_915106327 小时前
App 怎么上架 iOS?从准备资料到开心上架(Appuploader)免 Mac 上传的完整实战流程指南
android·macos·ios·小程序·uni-app·iphone·webview
青木狐8 小时前
关闭 macOS 屏幕捕捉 在录制或截图时显示的「录制指示浮窗」。
macos·mac
2501_9159214312 小时前
iOS 抓不到包怎么办?工程化排查与替代抓包方案(抓包/HTTPS/Charles代理/tcpdump)
android·ios·小程序·https·uni-app·iphone·tcpdump
taokexia14 小时前
SwiftUI 组件开发: 自定义下拉刷新和加载更多(iOS 15 兼容)
ios·swift
2501_9159184115 小时前
Fiddler抓包工具详解,HTTP/HTTPS抓包、代理设置与调试技巧一站式教程(含实战案例)
http·ios·小程序·https·fiddler·uni-app·webview
LvLuffy15 小时前
mac Android Studio配置adb环境(使用adb报错 adb: command not found)
macos·adb·android studio