在Swift中以编程方式切换视图

SRL*_*SRL 7 xcode viewcontroller swift

我想通过按下"感觉幸运"按钮切换到第二个视图.当我试用我的模拟器并按下它时,它就会变成黑屏.我怎么能解决这个问题?

@IBAction func FeelingLuckyPress(sender: UIButton) {

    let secondViewController:SecondViewController = SecondViewController()

    self.presentViewController(secondViewController, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*Rob 21

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

创造segue

然后,您可以选择该segue并为其提供唯一的故事板标识符,然后您可以使用该标识符执行segue:

performSegueWithIdentifier("SegueToSecond", sender: self)
Run Code Online (Sandbox Code Playgroud)

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

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

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


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