Instantiate and Present a viewController in Swift

前端 未结 16 1541
难免孤独
难免孤独 2020-11-22 13:04

Issue

I started taking a look of the new Swift on Xcode 6, and I tried some demo projects and tutorials. Now I am stuck at:

相关标签:
16条回答
  • 2020-11-22 13:16
    // "Main" is name of .storybord file "
    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    // "MiniGameView" is the ID given to the ViewController in the interfacebuilder
    // MiniGameViewController is the CLASS name of the ViewController.swift file acosiated to the ViewController
    var setViewController = mainStoryboard.instantiateViewControllerWithIdentifier("MiniGameView") as MiniGameViewController
    var rootViewController = self.window!.rootViewController
    rootViewController?.presentViewController(setViewController, animated: false, completion: nil)
    

    This worked fine for me when i put it in AppDelegate

    0 讨论(0)
  • 2020-11-22 13:17

    akashivskyy's answer works just fine! But, in case you have some trouble returning from the presented view controller, this alternative can be helpful. It worked for me!

    Swift:

    let storyboard = UIStoryboard(name: "MyStoryboardName", bundle: nil)
    let vc = storyboard.instantiateViewControllerWithIdentifier("someViewController") as! UIViewController
    // Alternative way to present the new view controller
    self.navigationController?.showViewController(vc, sender: nil)
    

    Obj-C:

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MyStoryboardName" bundle:nil];
    UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"someViewController"];
    [self.navigationController showViewController:vc sender:nil];
    
    0 讨论(0)
  • 2020-11-22 13:21

    I created a library that will handle this much more easier with better syntax:

    https://github.com/Jasperav/Storyboardable

    Just change Storyboard.swift and let the ViewControllers conform to Storyboardable.

    0 讨论(0)
  • 2020-11-22 13:22

    If you have a Viewcontroller not using any storyboard/Xib, you can push to this particular VC like below call :

     let vcInstance : UIViewController   = yourViewController()
     self.present(vcInstance, animated: true, completion: nil)
    
    0 讨论(0)
  • 2020-11-22 13:23

    Swift 4:

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let yourVC: YourVC = storyboard.instantiateViewController(withIdentifier: "YourVC") as! YourVC
    
    0 讨论(0)
  • 2020-11-22 13:23

    Swift 3 Storyboard

    let settingStoryboard : UIStoryboard = UIStoryboard(name: "SettingViewController", bundle: nil)
    let settingVC = settingStoryboard.instantiateViewController(withIdentifier: "SettingViewController") as! SettingViewController
    self.present(settingVC, animated: true, completion: {
    
    })
    
    0 讨论(0)
提交回复
热议问题