这个案例使用的是storyboard跳转的方式
为了方便弹窗动画是应用于各个UIViewController,所以独立出来行程一个协议。
在需要使用弹窗的时候,实现这个协议就行。

定义如下一个协议

import UIKit

enum Direction { case In, Out }

protocol Dimmable { }

extension Dimmable where Self: UIViewController {
    
    func dim(direction: Direction, color: UIColor = UIColor.black, alpha: CGFloat = 0.0, speed: Double = 0.0) {
        
        switch direction {
        case .In:
            let dimView = UIView(frame: view.frame)
            dimView.backgroundColor = color
            dimView.alpha = 0.0
            view.addSubview(dimView)
            dimView.translatesAutoresizingMaskIntoConstraints = false
            view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[dimView]|", options: [], metrics: nil, views: ["dimView": dimView]))
            view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[dimView]|", options: [], metrics: nil, views: ["dimView": dimView]))
            UIView.animate(withDuration: speed) { () -> Void in
                dimView.alpha = alpha
            }
            
        case .Out:
            UIView.animate(withDuration: speed, animations: { () -> Void in
                self.view.subviews.last?.alpha = alpha 
                }, completion: { (complete) -> Void in
                    self.view.subviews.last?.removeFromSuperview()
            })
        }
    }
}

使用时的只需要在UIViewController上实现上面的协议,并调用方法就行

class DemoViewController: UIViewController, Dimmable {
    
    let dimLevel: CGFloat = 0.8
    let dimSpeed: Double = 0.4
    
    // MARK: - Segues
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        dim(direction: .In, alpha: dimLevel, speed: dimSpeed)
    }

    @IBAction func unwindFromSecondary(segue: UIStoryboardSegue) {
        dim(direction: .Out, speed: dimSpeed)
    }
}