Search code examples
iosswiftsegue

Problem with transition between scenes programatically


My problem is that I can't find the correct code to transition between two scenes in IOS programatically. I have tried a few example codes, but none of them work as expected.

let vc storyboard!.instantiateViewController(withIdentifier: "savedMode") as! SavedModeViewController
        let navigationController = UINavigationController(rootViewController: vc)
        self.present(navigationController, animated: true, completion: nil)

This code goes to the new scene, but the back button doesn't appear in the left side of the navigation bar, and transition between scenes is wrong; instead of left to right animation, there is bottom to top animation.

let controller = storyboard?.instantiateViewController(withIdentifier: "savedMode") as! SavedModeViewController
        present(controller, animated: true, completion: nil)

This is the second code I have tried. The problem is that with this code, the navigation bar doesn't show at all in the second scene.

I have tried another way, but instead of second scene, the screen just turned black.


Solution

  • Calling present will present the new view controller modally over the current view controller.

    What you want is to push the new view controller onto the existing UINavigationController with pushViewController .

    if let savedVC = storyboard?.instantiateViewController(withIdentifier: "savedMode") as? SavedModeViewController, 
       let navigationController = self.navigationController {
    
        navigationController.pushViewController(savedVC, animated: true)
    
    } else {
    
        // TODO: Handle unexpected nil occurrences
        print("Error loading SavedModeViewController")
    
    }