Swift 重构: UIAlertController 富文本链接点击事件/用户隐私协议弹窗

·  阅读 518

需求:

最近重构项目代码尝试用 UIAlertController 实现富文本呈现及跳转事件,过程是曲折的,但结果是完美的。

Screenshot:

WechatIMG58.jpeg

核心源码:

@objc func showAlertAgreement() {
    let title = "用户协议和隐私政策"

    let linkDic = ["《用户协议》": "http://*",
                   "《隐私政策》": "http://*",]

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

    let attributedText = NSAttributedString.create(string, textTaps: Array(linkDic.keys))
    let alertVC = UIAlertController(title: title, message: nil, preferredStyle: .alert)
        .addActionTitles([kTitleCancell, "同意"]) { vc, action in
            DDLog(action.title)
        }

    alertVC.setValue(attributedText, forKey: kAlertMessage)
    alertVC.messageLabel?.addGestureTap { reco in
        reco.didTapLabelAttributedText(linkDic) { text, url in
            DDLog("\(text), \(url ?? "_")")
        }
    }
    alertVC.present()
}

//2021-08-12 17:47:59.674000+0800 AlertSheetStudyController.swift.showAlertAgreement()[line 409]: 《用户协议》, http://*
//2021-08-12 17:48:05.490000+0800 AlertSheetStudyController.swift.showAlertAgreement()[line 409]: 《隐私政策》, http://*
复制代码

@objc public extension UIAlertController{

    private var subView5: UIView? {
        guard let subView1: UIView = self.view.subviews.first,
              let subView2: UIView = subView1.subviews.first,
              let subView3: UIView = subView2.subviews.first,
              let subView4: UIView = subView3.subviews.first,
              let subView5: UIView = subView4.subviews.first
              else { return nil }
        return subView5
    }

    var titleLabel: UILabel? {
        guard let _ = self.title,
              let subView5 = subView5,
              subView5.subviews.count > 2,
              let label = subView5.subviews[1] as? UILabel
              else { return nil }
        return label
    }

    var messageLabel: UILabel? {
        guard let subView5 = subView5
              else { return nil }
        let messageLabelIndex = self.title == nil ? 1 : 2
        if subView5.subviews.count > messageLabelIndex,
           let label = subView5.subviews[messageLabelIndex] as? UILabel
           {
            return label
        }
        return nil
    }
}
复制代码

@objc public extension UITapGestureRecognizer {

    /// UILabel 富文本点击(仅支持 lineBreakMode = .byWordWrapping)
    func didTapLabelAttributedText(_ linkDic: [String: String], action: @escaping (String, String?) -> Void) {
        assert(((self.view as? UILabel) != nil), "Only supports UILabel")
        guard let label = self.view as? UILabel,
              let attributedText = label.attributedText
              else { return }

        // Create instances of NSLayoutManager, NSTextContainer and NSTextStorage
        let layoutManager = NSLayoutManager()
        let textContainer = NSTextContainer(size: CGSize.zero)
        let textStorage = NSTextStorage(attributedString: attributedText)
        // Configure layoutManager and textStorage
        layoutManager.addTextContainer(textContainer)
        textStorage.addLayoutManager(layoutManager)

        // Configure textContainer
        textContainer.lineFragmentPadding = 0.0
        textContainer.lineBreakMode = label.lineBreakMode
        textContainer.maximumNumberOfLines = label.numberOfLines

        let labelSize = label.bounds.size
        textContainer.size = labelSize

        // Find the tapped character location and compare it to the specified range
        let locationOfTouchInLabel = self.location(in: label)
        let textBoundingBox = layoutManager.usedRect(for: textContainer)
        let textContainerOffset = CGPoint(x:(labelSize.width - textBoundingBox.size.width)*0.5 - textBoundingBox.origin.x,
                                        y:(labelSize.height - textBoundingBox.size.height)*0.5 - textBoundingBox.origin.y)
        let locationOfTouchInTextContainer = CGPoint(x: locationOfTouchInLabel.x - textContainerOffset.x,
                                                   y: locationOfTouchInLabel.y - textContainerOffset.y)
        let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInTextContainer,
                                                          in: textContainer,                                                             fractionOfDistanceBetweenInsertionPoints: nil)

        //
        linkDic.forEach { e in
            let targetRange: NSRange = (attributedText.string as NSString).range(of: e.key)
            let isContain = NSLocationInRange(indexOfCharacter, targetRange)
            if isContain {
                action(e.key, e.value)
            }
        }
    }
}
复制代码

github

分类:
iOS
标签:
分类:
iOS
标签:
收藏成功!
已添加到「」, 点击更改