我以编程方式在iOS Swift项目中拥有多个View Controller.我没有故事板,如果可能的话,我想避免使用它们.有没有办法切换到另一个viewcontroller.swift
文件(我们将调用它view2.swift
)并让它成为按钮调用的函数的一部分?
我尝试过以下方法:
let storyboard: UIStoryboard = UIStoryboard(name: "myTabBarName", bundle: nil) let vc: UIViewController = storyboard.instantiateViewControllerWithIdentifier("myVCID") as UIViewController self.presentViewController(vc, animated: true, completion: nil)
上面的工作与故事板,但我希望另一个view2.swift
被称为.可以这样做吗?
对于那些获得空白/黑屏的人来说,这段代码对我有用.
let vc = self.storyboard?.instantiateViewController(withIdentifier: myVCID) as! myVCName self.present(vc, animated: true, completion: nil)
要为VC设置"标识符",只需转到故事板中VC的身份检查器.将"故事板ID"设置为您想要的标识符.请查看下面的图片以供参考.
试试这个:
let vc = ViewController() //change this to your class name self.presentViewController(vc, animated: true, completion: nil)
使用Swift3:
self.present(vc, animated: true, completion: nil)
对我来说,我在两个独立的导航控制器中有两个视图.我不得不使用上面的组合.
var vc = self.storyboard?.instantiateViewControllerWithIdentifier("WelcomeViewController") as! WelcomeViewController var navigationController = UINavigationController(rootViewController: vc) self.presentViewController(navigationController, animated: true, completion: nil)
let secondVC = self.storyboard?.instantiateViewController(withIdentifier: "VC-ID" as! yourViewController let navigationVC = UINavigationController(rootViewController: secondVC) self.present(navigationVC, animated: true, completion: nil)
Swift 3和Swift 4
let vc = self.storyboard?.instantiateViewController(withIdentifier: "idMyViewControllerName") as! MyViewControllerName self.present(vc, animated: true, completion: nil)
供参考,因为这个问题是谷歌的第一个结果.
该方法presentViewController
被该方法取代present
.
您可以像旧的一样使用它:
self.present(viewControllerToPresent, animated: true, completion: nil)
打开相机的示例:
let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.camera imagePicker.allowsEditing = false self.present(imagePicker, animated: true, completion: nil)
使用Swift 2.1+
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("settingsVC") as! SettingsViewController self.presentViewController(vc, animated: true, completion: nil)