swift - UIView弹窗协议

复制代码
//
//  DCUIAlertSystemAnimationProtocol.swift
//  doctor
//
//  Created by baitongtong on 2022/6/6.
//  Copyright © 2022 apple. All rights reserved.
//

import UIKit
import SnapKit

private var _coverKey = "DC_alertCoverKey"
private var _constraintsClosureKey = "DC_constraintsClosureKey"

protocol DCAlertSystemAnimationProtocol {
    
    /// 弹出
    func present()
    /// 消失
    func dismiss()
    
    /// 指定alertView约束 present 之前可设置
    func constrains(_ closure: @escaping (ConstraintMaker) -> Void)
}

extension DCAlertSystemAnimationProtocol where Self: UIView {

    
     private var _alertCover: UIView {
        set {
            objc_setAssociatedObject(self, &_coverKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get {
            return ((objc_getAssociatedObject(self, &_coverKey) as? UIView) ?? UIView())
        }
    }
    
    
    private var _constrainsClosure: ((ConstraintMaker) -> Void)? {
        set {
            objc_setAssociatedObject(self, &_constraintsClosureKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get {
            guard let closure = objc_getAssociatedObject(self, &_constraintsClosureKey) as? ((ConstraintMaker) -> Void) else {
                return nil
            }
            return closure
        }
    }
    
    func constrains(_ closure: @escaping (ConstraintMaker) -> Void) {
        _constrainsClosure = closure
    }
    
    func present() {
        let cover = UIView()
        cover.frame = UIScreen.main.bounds
        cover.backgroundColor = .init(white: 0, alpha: 0.25)
        cover.addSubview(self)
        
        if let constraintsClosure = _constrainsClosure {
            self.snp.makeConstraints(constraintsClosure)
        } else {
            self.snp.makeConstraints { make in
                make.center.equalToSuperview()
                make.left.equalTo(25)
            }
        }

        cover.alpha = 0
        self.alpha = 0.5
        
        UIApplication.shared.keyWindow?.addSubview(cover)
        cover.layoutIfNeeded()
        
        self.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
        
        UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseInOut) {
            cover.alpha = 1
            self.alpha = 1
            self.transform = CGAffineTransform.identity
        }
        _alertCover = cover
    }
    
    func dismiss() {
        UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseInOut) {
            self._alertCover.alpha = 0
        } completion: { isCompleted in
            if isCompleted {
                self.removeFromSuperview()
                self._alertCover.removeFromSuperview()
            }
        }
    }
}
复制代码

 

posted @   M·emor·Y  阅读(219)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
点击右上角即可分享
微信分享提示