Swift - Change the controller using the action button

How to switch view controller using UIButton ? Here is my code:

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

When I click the "Scan" button, it goes to the login form.

My view controller in Main.storyboard is like this

enter image description here

Please give me some advice if you can. Thanks.

+5
source share
4 answers

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) 
+13
source

One way is just a modal transition from the button. No IBOutlet required.

enter image description here

Programatically:

 @IBAction func scanButton (sender: UIButton!) { performSegueWithIdentifier("nextView", sender: self) } 

You must add modal segue and name the identifier. You are connecting VC1 to VC2.

+7
source

The easiest way is to create a UINavigationViewController. Then add the button to the current screen. Now click the control button and drag the button onto the target view controller. Here it is.

Source: iOs UINavigationViewController .

+1
source

Actually there is an answer without hardcoded code. In your storyboard, you can control the drag and drop of a button onto the next view controller and define segue there. This ensures that whenever you press a button, a segue will be called. You can see this in the "Connection Inspector" button when the sessions are running.

If you want to put data in the destination view controller, you can add inaction to the button and put the data in preparation for the segue function. The nice thing about this is that your triggers will still start from your button. This part will 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 hardcoded strings for segue identifiers, for storyboard identifiers, etc., and you can even prepare your destination view manager if necessary.

+1
source

Source: https://habr.com/ru/post/1205412/


All Articles