如何使用Swift从一个View Controller导航到另一个View Controller
我想从一个视图控制器导航到另一个。 我如何将下面的Objective-C代码转换成Swift?
UIViewController *viewController = [[self storyboard] instantiateViewControllerWithIdentifier:@"Identifier"]; UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:viewController]; [self.navigationController pushViewController:navi animated:YES];
为第二个视图控制器创build一个swift文件(SecondViewController.swift),并在适当的函数中input:
let secondViewController = self.storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as SecondViewController self.navigationController.pushViewController(secondViewController, animated: true)
Swift 2+
let mapViewControllerObj = self.storyboard?.instantiateViewControllerWithIdentifier("MapViewControllerIdentifier") as? MapViewController self.navigationController?.pushViewController(mapViewControllerObj!, animated: true)
在我的经验navigationController
是零,所以我改变了我的代码:
let next = self.storyboard?.instantiateViewControllerWithIdentifier("DashboardController") as! DashboardController self.presentViewController(next, animated: true, completion: nil)
不要忘记在StoryBoard
– > identity inspector
设置ViewController StoryBoard Id
如果你不想显示后退button(这是我的情况,因为我想在用户login后出现),这里是如何设置导航控制器的根:
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("YourViewController") as! YourViewController let navigationController = UINavigationController(rootViewController: vc) self.presentViewController(navigationController, animated: true, completion: nil)
SWIFT 3.01
let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "Conversation_VC") as! Conversation_VC self.navigationController?.pushViewController(secondViewController, animated: true)
Swift 3
let secondviewController:UIViewController = self.storyboard?.instantiateViewController(withIdentifier: "StoryboardIdOfsecondviewController") as? SecondViewController self.navigationController?.pushViewController(secondviewController, animated: true)
在迅速3
let nextVC = self.storyboard?.instantiateViewController(withIdentifier: "NextViewController") as! NextViewController self.navigationController?.pushViewController(nextVC, animated: true)
let objViewController = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController self.navigationController?.pushViewController(objViewController, animated: true)
在迅速4.0
var viewController: UIViewController? = storyboard().instantiateViewController(withIdentifier: "Identifier") var navi = UINavigationController(rootViewController: viewController!) navigationController?.pushViewController(navi, animated: true)
一个UINavagivationController的好函数
例:
func goToLoginView(){ if let loginView = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as? LoginViewController{ self.pushViewController(loginView, animated: true) } }