Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
745 views
in Technique[技术] by (71.8m points)

xcode - Switching Views Programmatically in 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)
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

create segue

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

performSegue(withIdentifier: "SegueToSecond", sender: self)

Alternatively, you can do something like:

guard let controller = storyboard?.instantiateViewController(withIdentifier: "Second") as? SecondViewController else {
    return
}
present(controller, animated: true) // or `show(controller, sender: self)`

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


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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...