Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

ios - Present a view controller, dismiss it and present a different one in Swift

So I have a root view controller that has a button that when the user pushes it, another view controller is presented. This second controller has a dismiss option that just comes back to the root view controller and a button that when the user touches it dismisses the current view controller so it goes back to the root view controller for a second and presents another one. Going to the first controller I use:

let vc = FirstController()
self.present(vc, animated: true, completion: nil)

And when in the other view controller I select the button that only dismisses I do this.

self.dismiss(animated: true, completion: nil)

So for the second controller that needs to dismiss and present another one I have tried the following:

self.dismiss(animated: true, completion: {
            let vc = SecondController()
            self.present(vc, animated: true, completion: nil)
        })

But I get an error:

Warning: Attempt to present <UINavigationController: 0xa40c790> on <IIViewDeckController: 0xa843000> whose view is not in the window hierarchy!
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The error occurs because you are trying to present SecondController from FirstController after you have dismissed FirstController. This doesn't work:

self.dismiss(animated: true, completion: {
    let vc = SecondController()

    // 'self' refers to FirstController, but you have just dismissed
    //  FirstController! It's no longer in the view hierarchy!
    self.present(vc, animated: true, completion: nil)
})

This problem is very similar to a question I answered yesterday.

Modified for your scenario, I would suggest this:

weak var pvc = self.presentingViewController

self.dismiss(animated: true, completion: {
    let vc = SecondController()
    pvc?.present(vc, animated: true, completion: nil)
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...