How to transition to a new view controller with code only using Swift

后端 未结 9 1556
半阙折子戏
半阙折子戏 2020-12-23 08:58

I want to transition from ViewController to secondViewController, when the user presses a UIButton, using code only in Swift.

//Function to transition
func          


        
9条回答
  •  余生分开走
    2020-12-23 09:44

    Your code is just fine. The reason you're getting a black screen is because there's nothing on your second view controller.

    Try something like:

    secondViewController.view.backgroundColor = UIColor.redColor();
    

    Now the view controller it shows should be red.

    To actually do something with secondViewController, create a subclass of UIViewController and instead of

    let secondViewController:UIViewController = UIViewController()
    

    create an instance of your second view controller:

    //If using code
    let secondViewController = MyCustomViewController.alloc()
    
    //If using storyboard, assuming you have a view controller with storyboard ID "MyCustomViewController"
    let secondViewController = self.storyboard.instantiateViewControllerWithIdentifier("MyCustomViewController") as UIViewController
    

提交回复
热议问题