如何在Swift中随机查看ViewControllers? [英] How to Segue Randomly to ViewControllers in Swift?

查看:154
本文介绍了如何在Swift中随机查看ViewControllers?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的Swift应用程序,我正在尝试使其成为一个按钮将导致我的Main.storyboard中的随机页面,但我不确定是否存在这样的方法。有没有办法让我这样做?

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?

推荐答案

以下是如何选择随机的ViewController 。对于我的例子,我选择使用 UINavigation Controller 并推送segues,但你可以像使用其他segue类型一样轻松地执行此操作。

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.

我创建了这个故事板:


  1. 单一开始查看应用程序模板。

  2. 在故事板中选择 ViewController ,然后编辑器 - >嵌入 - >菜单中的导航控制器

  3. 我添加了3个 ViewController s并将其背景设置为红色,绿色和右边的属性检查器中的蓝色。

  4. 下面我将讨论如何从 ViewController <连接segue / code>到红色,绿色和蓝色 ViewController s。

  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:

使这项工作的关键是从 ViewController ViewController 顶部的c $ c>图标,而不是从<$连接它C $ C>的UIButton 。在弹出窗口中,我选择了 push 作为segue类型。

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.

然后,单击segue箭头并给出segue标识符。我把它命名为pushGreen因为它是我的绿色ViewController的推送。

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.

我为红色的ViewController(segue:pushRed)和蓝色的ViewController(segue:重复了这个。 pushBlue)。

I repeated this for the red ViewController (segue: "pushRed") and the blue ViewController (segue: "pushBlue").

我在第一次添加 UIButton ViewController 并将其称为Go。这是按下它时的 IBAction

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)
}

这篇关于如何在Swift中随机查看ViewControllers?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆