Swift presentViewController

后端 未结 13 2004
悲&欢浪女
悲&欢浪女 2020-11-30 21:25

I programatically have multiple View Controllers in an iOS Swift Project. I do not have the storyboards and would like to avoid them if possible. Is there a way to switch to

相关标签:
13条回答
  • 2020-11-30 21:34

    I had a similar issue but in my case, the solution was to dispatch the action as an async task in the main queue

    DispatchQueue.main.async {
        let vc = self.storyboard?.instantiateViewController(withIdentifier: myVCID) as! myVCName
        self.present(vc, animated: true, completion: nil)
    }
    
    0 讨论(0)
  • 2020-11-30 21:38

    For reference, because this question is one of the first Google result.

    Breaking change in Swift 3:

    The method presentViewController is replaced by the method present.

    You can use it like the old one:

    self.present(viewControllerToPresent, animated: true, completion: nil)
    

    Example to open the camera:

    let imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = UIImagePickerControllerSourceType.camera
    imagePicker.allowsEditing = false
    self.present(imagePicker, animated: true, completion: nil)
    
    0 讨论(0)
  • 2020-11-30 21:39

    For those getting blank/black screens this code worked for me.

        let vc = self.storyboard?.instantiateViewController(withIdentifier: myVCID) as! myVCName
        self.present(vc, animated: true, completion: nil)
    

    To set the "Identifier" to your VC just go to identity inspector for the VC in the storyboard. Set the 'Storyboard ID' to what ever you want to identifier to be. Look at the image below for reference.

    0 讨论(0)
  • 2020-11-30 21:40

    Using Swift 2.1+

     let vc = self.storyboard?.instantiateViewControllerWithIdentifier("settingsVC") as! SettingsViewController
     self.presentViewController(vc, animated: true, completion: nil)
    

    0 讨论(0)
  • 2020-11-30 21:41

    Try this:

    let vc = ViewController() //change this to your class name
    self.presentViewController(vc, animated: true, completion: nil)
    

    With Swift3:

    self.present(vc, animated: true, completion: nil)
    
    0 讨论(0)
  • 2020-11-30 21:41

    Another possibility is that you do not have the XIB included in your Build target (which is what happened to me).

    This could happen if you have a different target for Dev, Test & Release Builds (which you should have anyway).

    0 讨论(0)
提交回复
热议问题