How to Segue Randomly to ViewControllers in Swift? [closed]

旧巷老猫 提交于 2019-11-28 02:15:41

问题


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:

  1. Starting with the Single View Application template.
  2. Selecting the ViewController in the Storyboard and then Editor->Embed In->Navigation Controller from the Menu.
  3. I added 3 more ViewControllers and set their backgrounds to red, green, and blue in the Attributes Inspector on the right.
  4. Below I talk about how to wire up the segues from the ViewController to the red, green, and blue ViewControllers.

    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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!