Swift - Change view controller using action button

2019-03-13 11:47发布

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

enter image description here

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

标签: ios swift xcode6
4条回答
三岁会撩人
2楼-- · 2019-03-13 12:25

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)
查看更多
做个烂人
3楼-- · 2019-03-13 12:29

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.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-03-13 12:45

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.

查看更多
The star\"
5楼-- · 2019-03-13 12:46

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.

查看更多
登录 后发表回答