Change view controller using action button

There is actually an answer without hardcoded code. In your storyboard, you can control drag the button to the next view controller and define the segue there. This will ensure that whenever you press the button, the segue will trigger. You can see this in the button's "Connections Inspector" at the triggered segues.

If you want to do put data in the destination view controller, you can add an inaction to the button and put the data in prepare for segue function. The cool thing about this is that your triggered segues will still trigger from your button. This part would look like this:

    @IBAction func buttonPressed(_ sender: UIButton) {
        someImportantData = "some data if needed"
        //no need to trigger segue :)
    }

    //not your case, but in order to understand the sage of this approach
    @IBAction func button2Pressed(_ sender: UIButton) {
        someImportantData = "some data2 if needed"
        //no need to trigger segue :)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        //retrieve the destination view controller for free
        if let myDestincationViewController = (segue.destination as? MyDestincationViewController) {
            myDestincationViewController.someImportantData = someImportantData
        }
    }

This way you do not need any hardcoded strings for segue identifiers, for storyboard identifiers, etc. and you can even prepare your destination view controller if needed.


I already found the answer

let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("nextView") as NextViewController
self.presentViewController(nextViewController, animated:true, completion:nil)

The easiest way is to create a UINavigationViewController. Then add a Button to the current screen. Now press control and drag the Button to the Target View Controller. Thats it.

Source: iOs UINavigationViewController.


One way is to just have a modal segue from a button. No IBOutlet required.

enter image description here

Programatically:

@IBAction func scanButton (sender: UIButton!) {

    performSegueWithIdentifier("nextView", sender: self)

}

You should add a modal segue and name the identifier. You connect the VC1 to VC2.

Tags:

Ios

Swift

Xcode6