How to create a popup with animation in Swift iOS 12.05.2020

We are going to use two ViewControllers. On first one we will have one Button with action to start the second ViewController. Wich will be our popup.

The first ViewController has name StartViewController and contains following code

class StartViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func goTapped(_ sender: Any) {
        let popUpVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "popUpVC") as! PopupViewController
        self.addChild(popUpVC)
        popUpVC.view.frame = self.view.frame
        self.view.addSubview(popUpVC.view)

        popUpVC.didMove(toParent: self)
    }
}

The second ViewController has PopupViewController name. In Storyboard add popUpVC id for PopupViewController in Storyboard ID field.

Place UIView on PopupViewController and create a popupView outlet. Add a Close button above popupView view and create a btnClose action.

class PopupViewController: UIViewController {
    @IBOutlet weak var popupView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        popupView.layer.cornerRadius = 16
        view.backgroundColor = UIColor.black.withAlphaComponent(0.75)

        moveIn()
    }

    @IBAction func closeTapped(_ sender: Any) {
        moveOut()
    }

    func moveIn() {
        self.view.transform = CGAffineTransform(scaleX: 1.35, y: 1.35)
        self.view.alpha = 0.0

        UIView.animate(withDuration: 0.24) {
            self.view.transform = CGAffineTransform.identity
            self.view.alpha = 1.0
        }
    }

    func moveOut() {
        UIView.animate(withDuration: 0.24, animations: {
            self.view.transform = CGAffineTransform(scaleX: 1.35, y: 1.35)
            self.view.alpha = 0.0
        }) { _ in
            self.view.removeFromSuperview()
        }
    }

}

That's it.

Useful links