Swift - Change view controller using action button

2019-03-13 11:41发布

问题:

How can I switch the view controller using UIButton? Here is my code:

@IBAction func scanAction(sender: AnyObject) {
      //switch view controller 
}

When I click the Scan button, it will go to a login form.

My view controller in Main.storyboard is like this

Please give me some advice if you can. Thank you.

回答1:

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)


回答2:

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

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.



回答3:

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.



回答4:

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.



标签: ios swift xcode6