【问题标题】:How to Navigate from one View Controller to another using Swift如何使用 Swift 从一个视图控制器导航到另一个视图控制器
【发布时间】:2014-07-25 03:35:04
【问题描述】:

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

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

【问题讨论】:

标签: ios swift uinavigationcontroller uikit viewcontroller


【解决方案1】:

为第二个视图控制器创建一个 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,您好,您的视图控制器可以使用 Storyboard 创建并将您的 firstViewController 指定为 rootViewController。您的导航控制器 (swift) 类将如下所示:import UIKitclass SwiftNavigationController: UINavigationController { init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) // Custom initialization }`` override func viewDidLoad() { super.viewDidLoad() }
  • 我也有同样的问题,我被困在如何从一个 ViewController 导航到另一个。当我尝试此代码时,我收到此错误:unexpectedly found nil while unwrapping an Optional value 在代码的第二行。请帮忙
  • 我遇到了有关动画的问题:参数如下:“无法转换表达式的类型 '$T7??'输入“BooleanLiteralConvertible””。
  • 您需要确保控制器嵌入到 NavigationController 中才能正常工作,否则会出错。
【解决方案2】:

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

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

别忘了在 StoryBoard 中设置 ViewController StoryBoard Id -> identity inspector

【讨论】:

  • 这是因为您的视图控制器没有在导航视图控制器中消退。
【解决方案3】:

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

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

【讨论】:

    【解决方案4】:

    SWIFT 3.01

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

    【讨论】:

      【解决方案5】:

      斯威夫特 3

      let secondviewController:UIViewController =  self.storyboard?.instantiateViewController(withIdentifier: "StoryboardIdOfsecondviewController") as? SecondViewController
      
      self.navigationController?.pushViewController(secondviewController, animated: true)
      

      【讨论】:

        【解决方案6】:
        let objViewController = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
        self.navigationController?.pushViewController(objViewController, animated: true)
        

        【讨论】:

        • 能否请您简要解释一下您的代码的作用、它解决问题的原因以及它与所有其他答案的不同之处。
        • 这里我使用 storyboard id 作为标识符。通过引用(objViewController)将控件推送到 View Controller 类
        【解决方案7】:

        在 Swift 3 中

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

        【讨论】:

          【解决方案8】:

          在 Swift 4.0 中

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

          【讨论】:

            【解决方案9】:

            在 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) 
            } 
            

            【讨论】:

              【解决方案10】:

              斯威夫特 4

              你可以通过推导航控制器来切换屏幕首先你必须用UIViewController设置导航控制器

              let vc = self.storyboard?.instantiateViewController(withIdentifier: "YourStoryboardID") as! swiftClassName
              
              self.navigationController?.pushViewController(vc, animated: true)
              

              【讨论】:

                【解决方案11】:
                let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                let home = storyBoard.instantiateViewController(withIdentifier: "HOMEVC") as! HOMEVC
                navigationController?.pushViewController(home, animated: true);
                

                【讨论】:

                • 我认为这不是 Swift 或 Objc 语法
                【解决方案12】:

                斯威夫特 5

                使用 Segue 执行从一个 View Controller 到另一个 View Controller 的导航:

                performSegue(withIdentifier: "idView", sender: self)
                

                这适用于 Xcode 10.2。

                【讨论】:

                • 转场类型?
                【解决方案13】:

                在 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)
                }
                

                【讨论】:

                  【解决方案14】:

                  Swift 5 更新:

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

                  不要忘记更新两个视图控制器的 Storyboard ID!

                  【讨论】:

                  • 你知道,Swift 的版本是 5.4。
                  【解决方案15】:

                  更好的实践 Swift 5.0

                  更具可重用性和可读性

                  创建协议

                  protocol Storyboarded { }
                  

                  现在创建协议的扩展

                  extension Storyboarded where Self: UIViewController {
                      
                      static func instantiateFromMain() -> Self {
                          let storyboardIdentifier = String(describing: self)
                          // `Main` can be your stroyboard name.
                          let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
                          
                          guard let vc = storyboard.instantiateViewController(withIdentifier: storyboardIdentifier) as? Self else {
                              fatalError("No storyboard with this identifier ")
                          }
                          return vc
                      }
                  }
                  

                  如何使用

                    let vc = MyViewController.instantiateFromMain()
                    //here you can pass any data to the next view controller. for example we have a variable with name `myString` in our next view contoller and we want to pass the data my `self viewController`
                    vc.myString = "This string passed by MyViewController ViewController"
                    self.navigationController?.pushViewController(vc, animated: true)
                  

                  注意:-您需要在情节提要上提供与 UIViewController 类相同的标识符。检查下面的示例

                  【讨论】:

                    【解决方案16】:

                    对于 Swift 4 & 5 用户可以使用这种方式

                    斯威夫特 5

                     let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                     let vc = storyBoard.instantiateViewController(withIdentifier: "YourViewController") as! YourViewController
                     self.navigationController?.pushViewController(vc, animated: true)
                    

                    斯威夫特 4

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

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2016-09-06
                      • 1970-01-01
                      • 2013-03-12
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      相关资源
                      最近更新 更多