-3
let SecondViewController = 
self.storyboard?.instantiateViewController(withIdentifier: 
"SecondViewController") as! SecondViewController

self.navigationController?.pushViewController(SecondViewController, 
animated: true)

For some reason this doesn't work. Any ideas?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Reid Brown
  • 11
  • 2
  • I think "present" is what you are looking for rather than push.. You should just be able to write present(SecondViewController, animated: true, completion: nil) – user2877496 Jun 28 '17 at 18:45
  • 1
    The code you posted will only work if `self` is in a navigation controller. – rmaddy Jun 28 '17 at 18:49
  • I tried that and it didnt work @use – Reid Brown Jun 28 '17 at 18:56
  • Does navigationController exist? I see its an optional so if it doesn't exist it will just skip the line – user2877496 Jun 28 '17 at 19:01
  • 1
    Possible duplicate of [How to Navigate from one View Controller to another using Swift](https://stackoverflow.com/questions/24038215/how-to-navigate-from-one-view-controller-to-another-using-swift) – ZGski Jun 28 '17 at 19:05
  • You need to add the symbolicated crash log and indicate the line of code that causes the crash. – Robotic Cat Jun 28 '17 at 22:44

1 Answers1

2

Replace

self.navigationController?.pushViewController(SecondViewController, 
animated: true)

with

self.navigationController?.present(SecondViewController, animated: true, completion: nil)

Edit: To avoid the optionals you should also do one of the following:

guard let navController = self.navigationController else { return }
navController.present(SecondViewController, animated: true, completion: nil)

or

if let nacVontroller = self.navigationController {
    navController.present(SecondViewController, animated: true, completion: nil)
}

Edit2: You should also avoid force unwrapping your SecondViewController using one of the above methods as well. Although that is not your current issue.

Jerland2
  • 1,096
  • 11
  • 28
  • Hmm.. When you said it didn't work, what happened when you tried it? Can you elaborate a little? Ex: Did it crash? Or did it just not do anything? Edit: Does your app have a tabbar as a parent view? (Does the screen you are on have a tabbar) – Jerland2 Jun 28 '17 at 18:58
  • @ReidBrown Check your storyboard to ensure that it doesn't have broken outlets, also check to make sure that the view controller is assigned the class "SecondViewController" – Jerland2 Jun 28 '17 at 19:03
  • This is all happens when I click a button just fyi I don't know if that has any significance. – Reid Brown Jun 28 '17 at 19:05
  • @ReidBrown Have you checked that your iboutlet connections are linked properly? If they are not this will result in a SIGBART. Specifically check both Views, buttons, button actions. – Jerland2 Jun 28 '17 at 19:07