Swift 重構(gòu): UIAlertController 富文本鏈接點(diǎn)擊事件/用戶隱私協(xié)議彈窗

需求:

最近重構(gòu)項(xiàng)目代碼嘗試用 UIAlertController 實(shí)現(xiàn)富文本呈現(xiàn)及跳轉(zhuǎn)事件,過程是曲折的,但結(jié)果是完美的。

Screenshot:

WechatIMG58.jpeg

核心源碼:

@objc func showAlertAgreement() {
    let title = "用戶協(xié)議和隱私政策"

    let linkDic = ["《用戶協(xié)議》": "http://*",
                   "《隱私政策》": "http://*",]

    let string = "\t用戶協(xié)議和隱私政策請您務(wù)必審值閱讀、充分理解 “用戶協(xié)議” 和 ”隱私政策” 各項(xiàng)條款,包括但不限于:為了向您提供即時(shí)通訊、內(nèi)容分享等服務(wù),我們需要收集您的設(shè)備信息、操作日志等個(gè)人信息。\n\t您可閱讀《用戶協(xié)議》和《隱私政策》了解詳細(xì)信息。如果您同意,請點(diǎn)擊 “同意” 開始接受我們的服務(wù);"

    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]: 《用戶協(xié)議》, 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 富文本點(diǎn)擊(僅支持 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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容