xcode 在 Swift 中以编程方式切换视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27650140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Switching Views Programmatically in Swift
提问by SRL
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)
}
回答by Rob
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)
where "Second" is a storyboard identifier I specified for that destination scene in Interface Builder.
其中“Second”是我在 Interface Builder 中为该目标场景指定的故事板标识符。
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.
顺便说一下,如果您以编程方式或使用 NIB 创建目标场景,还有其他选择,但故事板更常见,因此我在上面的示例中重点介绍了这一点。