问题
For my Swift app, I'm trying to make it so that a button will lead to a random page in my Main.storyboard but I'm not sure if such a method exists. Is there a way for me to do this?
回答1:
Here is how you can segue to a random ViewController
. For my example, I chose to use a UINavigation Controller
and push segues, but you could do this just as easily with other segue types.
I created this Storyboard by:
- Starting with the Single View Application template.
- Selecting the
ViewController
in the Storyboard and then Editor->Embed In->Navigation Controller from the Menu. - I added 3 more
ViewController
s and set their backgrounds to red, green, and blue in the Attributes Inspector on the right. Below I talk about how to wire up the segues from the
ViewController
to the red, green, and blueViewController
s.Here is an overview of my final Storyboard:

The key to making this work is to wire up your segues from the ViewController
icon at the top of your ViewController
instead of connecting it from the UIButton
. In the pop up, I chose push
as the segue type.

After that, click on the segue arrow and give the segue an Identifier. I named mine "pushGreen" because it is a push segue to my green ViewController.

I repeated this for the red ViewController (segue: "pushRed") and the blue ViewController (segue: "pushBlue").
I added a UIButton
to my first ViewController
and called it "Go". Here is the IBAction
for when it is pressed:
@IBAction func goPressed(sender: UIButton) {
let segues = ["pushRed", "pushGreen", "pushBlue"]
let index = Int(arc4random_uniform(UInt32(segues.count)))
let segueName = segues[index]
self.performSegueWithIdentifier(segueName, sender: self)
}
来源:https://stackoverflow.com/questions/27085872/how-to-segue-randomly-to-viewcontrollers-in-swift