2

I'm wondering how would I be able to remove a view controller that the app is not currently on?

Let's say I segue from OldViewController to NewViewController. Once NewVC loads, how can I have it delete the OldVC, while the app is still on the NewVC?

EvanOgo
  • 541
  • 4
  • 10

1 Answers1

1

I've tried unwind segues and dismiss nested presentingViewController solutions, but both still have the issue with intermediate controller being visible during animation.

Then I found this suggestion which I modified with different snapshot generation, since it was not working properly for me.

Probably not the best solution, but still may be helpful.

Helper extensions:

extension UIViewController {
    func dismissModalStack(animated: Bool, completion: (()->Void)?) {
        guard let snapshot = UIApplication.shared.delegate?.window??.snapshotView() else { return }
        self.presentedViewController?.view.insertSubview(snapshot, at: Int.max)
        self.dismiss(animated: true, completion: completion)
    }
}

extension UIView {
    public func snapshotImage() -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
        drawHierarchy(in: bounds, afterScreenUpdates: false)
        let snapshotImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return snapshotImage
    }

    public func snapshotView() -> UIView? {
        guard let snapshotImage = snapshotImage() else { return nil }
        return UIImageView(image: snapshotImage)
    }
}

Usage:

In the last presented view controller:

@IBAction func dismissPressed() {
    self.presentingViewController?.presentingViewController?.dismissModalStack(animated: true, completion: nil)
}

Result:

enter image description here

Community
  • 1
  • 1
alexburtnik
  • 7,243
  • 4
  • 27
  • 63