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?

5
  • And what controller do you want to be shown instead of OldViewController? Commented Nov 9, 2016 at 22:47
  • A -> B (presented modally over A) -> C (presented modally over B) and you want to return from C to A, right? Commented Nov 9, 2016 at 22:48
  • I just edited the post to give an idea of the viewcontroller hierarchy Commented Nov 9, 2016 at 22:49
  • Can you post your storyboard? How do you setup each segues? Commented Nov 9, 2016 at 23:33
  • I think I'll just rephrase the question so its more straight forward Commented Nov 9, 2016 at 23:39

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.