简体   繁体   中英

When changing view controllers, new controller appears, but disappears almost immediately

I have this code in one of my IBAction (when a button is pressed), which is supposed to bring up a new view controller.

let addAlertVC = self.storyboard?.instantiateViewController(withIdentifier: "addAlert")

self.present(addAlertVC!, animated: false, completion: nil)

However, when I run the app and press the button that's supposed to take me to the new viewcontroller , but then I'm stuck with the original viewcontroller . I have put a print statement in the viewDidAppear function in the new view controller, and it is printing out whenever I press the button, so the new controller is definitely appearing. I have not dismissed the new controller anywhere in my app.

I have used the same code in other parts of my app, so I'm extremely confused as to why it's not working this time.

Any help would be greatly appreciated.

EDIT: I fixed my code. It turns out it wasn't how I was calling the view controller that was wrong, it was my button. Once I deleted and re-added the button, my code now works.

There is a good chance that your view controller is deallocated after you present it.

Try to declare your view controller outside of the function, in your controller. Something like:

class ViewController{

    var addAlertVC:UIViewController?

    ...

    func someFunction(){
        addAlertVC = self.storyboard?.instantiateViewController(withIdentifier: "addAlert")

        self.present(addAlertVC!, animated: false, completion: nil)
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM