24
votes

In Swift I have a button created programmaticaly using:

var button = UIBarButtonItem(title: "Tableau", style: .Plain, target: self, action: "tabBarTableauClicked")

I want that when the user clicks the button it changes viewControllers. Here is the code for tabBarTableauClicked:

func tabBarTableauClicked(){
    performSegueWithIdentifier("tableau", sender: self)
}

But it is obviously not working because there is no segue with an identifier called "tableau".

And I can't create a segue using Ctrl + click the button and drag to the second viewController because the button is created programatically and not in the Storyboard.

How can I create a segue with an identifier programmatically in Swift?

1
Segues can't be created outside of the storyboard. stackoverflow.com/questions/9674685/…user3746428
Are your first and second view controllers in the storyboard?vacawama
Yes they are but the button is notClément Bisaillon
As long as you have both viewcontrollers in storyboard then you can create segues there and fire them programmatically. You don't need a button in the storyboard to fire a segue, having the viewcontroller which that button resides in is enough!Honey

1 Answers

88
votes

Here is how to set up a segue so that it can be called programmatically.

  • Control drag from the ViewController icon in the first view controller to the second view controller.
  • Click on the segue arrow between the two view controllers, and in the Attributes Inspector on the right, give the segue an Identifier (tableau in your case).
  • Then you can trigger the segue with performSegueWithIdentifier in your code.

enter image description here

You can read more about setting up and using segues here.