如何使用Swift从一个View Controller导航到另一个


84

我想从一个视图控制器导航到另一个。如何将以下Objective-C代码转换为Swift?

UIViewController *viewController = [[self storyboard] instantiateViewControllerWithIdentifier:@"Identifier"];
UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:viewController];
[self.navigationController pushViewController:navi animated:YES];

Answers:


208

为第二个视图控制器创建一个swift文件(SecondViewController.swift),并在适当的函数中键入以下内容:

let secondViewController = self.storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as SecondViewController
self.navigationController.pushViewController(secondViewController, animated: true)


迅捷2+

let mapViewControllerObj = self.storyboard?.instantiateViewControllerWithIdentifier("MapViewControllerIdentifier") as? MapViewController
self.navigationController?.pushViewController(mapViewControllerObj!, animated: true)

斯威夫特4

let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "IKDetailVC") as? IKDetailVC
self.navigationController?.pushViewController(vc!, animated: true)

@audrey,您好,如何设置navigationController?
Sanjivani 2014年

@Sanjivani,您好,您可以使用Storyboard创建视图控制器并将您的firstViewController分配为rootViewController。您的导航Controller(swift)类将如下所示: import UIKit class SwiftNavigationController: UINavigationController { init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) // Custom initialization }`` override func viewDidLoad() { super.viewDidLoad() }
Audrey Sobgou Zebaze 2014年

3
我也有同样的问题,我被困在如何从一个ViewController导航到另一个ViewController上。当我尝试此代码时,出现此错误:unexpectedly found nil while unwrapping an Optional value在代码的第二行。请帮忙
Raghavendra 2014年

1
我在动画:参数方面遇到问题,例如:“无法转换表达式的类型'$ T7 ??” 键入“ BooleanLiteralConvertible””。
Morkrom 2014年

2
您需要确保将控制器嵌入到NavigationController中,才能正常工作,否则会出现错误。
角北

35

以我的经验navigationController为零,所以我将代码更改为:

let next = self.storyboard?.instantiateViewControllerWithIdentifier("DashboardController") as! DashboardController
self.presentViewController(next, animated: true, completion: nil)

不要忘记设置ViewController StoryBoard IdStoryBoard->中identity inspector


2
这是因为您的视图控制器没有在Navigation View Controller中消失。
弗朗西斯·雷诺兹

18

如果您不希望显示“后退”按钮(这是我的情况,因为我想在用户登录后显示),这是设置导航控制器根目录的方法:

let vc = self.storyboard?.instantiateViewControllerWithIdentifier("YourViewController") as! YourViewController
        let navigationController = UINavigationController(rootViewController: vc)
        self.presentViewController(navigationController, animated: true, completion: nil)

16

SWIFT 3.01

let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "Conversation_VC") as! Conversation_VC
self.navigationController?.pushViewController(secondViewController, animated: true)

8

在迅速4.0

var viewController: UIViewController? = storyboard().instantiateViewController(withIdentifier: "Identifier")
var navi = UINavigationController(rootViewController: viewController!)
navigationController?.pushViewController(navi, animated: true)

4

迅捷3

let secondviewController:UIViewController =  self.storyboard?.instantiateViewController(withIdentifier: "StoryboardIdOfsecondviewController") as? SecondViewController

self.navigationController?.pushViewController(secondviewController, animated: true)

4

在Swift 4.1和Xcode 10中

在这里,AddFileViewController是第二个视图控制器。

故事板ID为AFVC

let next = self.storyboard?.instantiateViewController(withIdentifier: "AFVC") as! AddFileViewController
self.present(next, animated: true, completion: nil)

//OR

//If your VC is DashboardViewController
let dashboard = self.storyboard?.instantiateViewController(withIdentifier: "DBVC") as! DashboardViewController
self.navigationController?.pushViewController(dashboard, animated: true)

如果需要,请使用螺纹。

例如:

DispatchQueue.main.async { 
    let next = self.storyboard?.instantiateViewController(withIdentifier: "AFVC") as! AddFileViewController
    self.present(next, animated: true, completion: nil) 
}

如果您想在一段时间后移动

例如:

//To call or execute function after some time(After 5 sec)
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
    let next = self.storyboard?.instantiateViewController(withIdentifier: "AFVC") as! AddFileViewController
    self.present(next, animated: true, completion: nil) 
} 

2

迅速3

let nextVC = self.storyboard?.instantiateViewController(withIdentifier: "NextViewController") as! NextViewController        
self.navigationController?.pushViewController(nextVC, animated: true)

2
let objViewController = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
self.navigationController?.pushViewController(objViewController, animated: true)

您能否简要说明一下代码的作用,为什么解决了问题以及它与所有其他答案的不同之处。
JJJ

在这里,我使用情节提要ID作为标识符。通过引用(objViewController)将控件推送到View Controller类
Davender Verma,

2
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let home = storyBoard.instantiateViewController(withIdentifier: "HOMEVC") as! HOMEVC
navigationController?.pushViewController(home, animated: true);

我认为它不是Swift或Objc语法
SPatel

1

斯威夫特4

您可以通过首先按下导航控制器来切换屏幕,首先必须使用UIViewController设置导航控制器

let vc = self.storyboard?.instantiateViewController(withIdentifier: "YourStoryboardID") as! swiftClassName

self.navigationController?.pushViewController(vc, animated: true)


1

在AppDelegate中,您可以这样编写...

var window: UIWindow?

fileprivate let navigationCtrl = UINavigationController()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    self.createWindow()

    self.showLoginVC()

    return true
}

func createWindow() {
    let screenSize = UIScreen.main.bounds
    self.window = UIWindow(frame: screenSize)
    self.window?.backgroundColor = UIColor.white
    self.window?.makeKeyAndVisible()
    self.window?.rootViewController = navigationCtrl
}

func showLoginVC() {
    let storyboardBundle = Bundle.main
    // let storyboardBundle = Bundle(for: ClassName.self) // if you are not using main application, means may be you are crating a framework or library you can use this statement instead
    let storyboard = UIStoryboard(name: "LoginVC", bundle: storyboardBundle)
    let loginVC = storyboard.instantiateViewController(withIdentifier: "LoginVC") as! LoginVC
    navigationCtrl.pushViewController(loginVC, animated: false)
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.