How to transition screens programmatically with Swift?

Asked

Viewed 948 times

1

Good evening, guys. I’m trying to do some programmatically transitions of the screen with Swift, but I can’t. I tried to use navigationController, but it didn’t work, it always gives a different error. The screens are arranged in the same storeboard, I just need to move from screen 1 to screen 2. I tried to use protocols too, but I could not and I got more rolled up. Below is the code I’m trying to use to make the screen change, this snippet is in Viewcontroller:

@IBAction func btnSegue() {
    let newTela = TelaDoisViewController(delegate: self)

    if let navigation = navigationController {
        navigation.pushViewController(newTela, animated: true)
    }

}

Thanks for your help.

2 answers

1

To use the navigation the Viewcontroller needs to be "inside" a navigation.

But if Voce wants to simply show another Voce view you can use the following code:

let vc = ViewController() //Aqui você vai estanciar a sua ViewController de destino.
self.presentViewController(vc, animated: true, completion: nil)

1


If you are using NavigationController:

@IBAction func chamarNavigationController() {
   let storyBoard = UIStoryboard(name: "Main", bundle: nil)
   let novoNavigation = storyBoard.instantiateViewControllerWithIdentifier("NavViaCodigo")
   self.navigationController?.pushViewController(novoNavigation, animated: true)
}

// voltar pro navigation anterior
@IBAction func voltarProNavigationAnterior() {
   navigationController?.popViewControllerAnimated(true)
}

If you’re using ViewController:

@IBAction func chamarViewController() {
  let storyBoard = UIStoryboard(name: "Main", bundle: nil)
  let novoViewController = storyBoard.instantiateViewControllerWithIdentifier("ViewViaCodigo")
  self.presentViewController(novoViewController, animated: true, completion: nil)
}

// voltar pro viewController anterior
@IBAction func voltarPraViewAnterior() {
  self.dismissViewControllerAnimated(true, completion: nil)
}

ps.: I made an example of how to make these transitions using Segue and programaticamente if you want to take a look >> Code example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.