美文网首页
iOS UITextView 富文本协议高亮链接点击

iOS UITextView 富文本协议高亮链接点击

作者: SoaringHeart | 来源:发表于2020-04-17 17:32 被阅读0次
Simulator Screen Shot - iPhone 6s Plus - 2020-04-17 at 17.28.44.png
@objcMembers class NNAgreementAlertController: UIViewController {

    func setupContent() {
        title = "用户协议和隐私政策"
        
        let tapTexts = ["《用户协议》", "《隐私政策》",];
        let tapUrls = ["", "",];
        let string = "\t用户协议和隐私政策请您务必审值阅读、充分理解 “用户协议” 和 ”隐私政策” 各项条款,包括但不限于:为了向您提供即时通讯、内容分享等服务,我们需要收集您的设备信息、操作日志等个人信息。\n\t您可阅读\(tapTexts[0])和\(tapTexts[1])了解详细信息。如果您同意,请点击 “同意” 开始接受我们的服务;"
        textView.setupUserAgreements(string, tapTexts: tapTexts, tapUrls: tapUrls)
        textView.delegate = self
    }
}

extension NNAgreementAlertController: UITextViewDelegate{
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        DDLog(URL.absoluteString)
        guard let urlString = URL.absoluteString.components(separatedBy: "_").last else { return false}
        UIApplication.openURLStr(urlString, prefix: "http://")
        return true
    }
}

@objc public extension UITextView{

    /// 用户协议点击跳转配制方法
    func setupUserAgreements(_ content: String, tapTexts: [String], tapUrls: [String], tapColor: UIColor = UIColor.theme) {
        let attDic = [NSAttributedString.Key.foregroundColor: self.textColor ?? UIColor.gray,
                      NSAttributedString.Key.font: self.font ?? UIFont.systemFont(ofSize: 16)
        ]
        
        let attString = NSMutableAttributedString(string: content, attributes: attDic as [NSAttributedString.Key : Any])
        for e in tapTexts.enumerated() {
            let nsRange = (attString.string as NSString).range(of: e.element)
            attString.addAttribute(NSAttributedString.Key.link, value: "\(e.offset)_\(tapUrls[e.offset])", range: nsRange)
        }
        
        let linkAttDic = [NSAttributedString.Key.foregroundColor : tapColor,
        ]
        linkTextAttributes = linkAttDic
        attributedText = attString
        isSelectable = true
        isEditable = false
    }
}

@objc public extension UIApplication{

    /// 打开网络链接(prefix为 http://或 tel:// )
    static func openURLStr(_ urlStr: String, prefix: String = "http://") -> Bool {

        var tmp = urlStr;
        if urlStr.hasPrefix(prefix) == false {
            tmp = prefix + urlStr;
        }
        
        guard let url = URL(string:tmp) else { return false}
        let canOpenUrl = UIApplication.shared.canOpenURL(url)
        if canOpenUrl == true {

            if #available(iOS 10.0, *) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            } else {

                UIApplication.shared.openURL(url);
            }
        } else {
            print("链接无法打开!!!\n%@",url as Any);
        }
        return canOpenUrl;
    }
}

相关文章

网友评论

      本文标题:iOS UITextView 富文本协议高亮链接点击

      本文链接:https://www.haomeiwen.com/subject/hriyvhtx.html