在 Swift 中以编程方式切换视图 [英] Switching Views Programmatically in Swift

查看:31
本文介绍了在 Swift 中以编程方式切换视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过按感觉很幸运"按钮切换到第二个视图.当我试用我的模拟器并按下它时,它只会进入黑屏.我该如何解决这个问题?

I am trying to switch to the second view by pressing the "feeling lucky" button. When I try out my simulator and press it, it just goes to a black screen. How could I fix this?

@IBAction func FeelingLuckyPress(sender: UIButton) {

    let secondViewController:SecondViewController = SecondViewController()

    self.presentViewController(secondViewController, animated: true, completion: nil)
}

推荐答案

您可以通过控制从第一个场景顶部的视图控制器图标拖动到第二个场景,在故事板中的两个场景之间添加转场:

You can add a segue between the two scenes in your storyboard by control dragging from the view controller icon at the top of the first scene to the second scene:

然后您可以选择该转场并为其指定一个唯一的故事板标识符,然后您就可以使用该标识符执行转场:

You can then select that segue and give it a unique storyboard identifier, and then you can just perform the segue using that identifier:

performSegueWithIdentifier("SegueToSecond", sender: self)

<小时>

或者,您可以执行以下操作:


Alternatively, you can do something like:

let controller = storyboard?.instantiateViewControllerWithIdentifier("Second") as SecondViewController
presentViewController(controller, animated: true, completion: nil)

其中Second"是我在 Interface Builder 中为该目标场景指定的故事板标识符.

where "Second" is a storyboard identifier I specified for that destination scene in Interface Builder.

顺便说一下,如果您以编程方式或使用 NIB 创建目标场景,还有其他选择,但故事板更为常见,因此我在上面的示例中重点介绍了这一点.

By the way, there are alternatives if you're creating your destination scene programmatically or using NIBs, but storyboards are more common, so I focused on that in my examples above.

这篇关于在 Swift 中以编程方式切换视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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