【问题标题】:Swift: Can't use navigationController.pushViewController inside a functionSwift:不能在函数中使用 navigationController.pushViewController
【发布时间】:2019-03-12 18:32:44
【问题描述】:

我正在使用下面的代码以编程方式在视图之间转换,并且重复了很多次,所以我想创建一个全局函数,但我似乎无法掌握它。

代码在 ViewController 类中调用时有效,所以我想问题是我的函数不知道我想在哪个 VC 上调用 navigationController.pushViewController,但我也不知道如何引用 VC作为传递给函数的参数,或者更好的是使用 .self 之类的东西来获取调用函数的当前 VC 类。

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "ExamplesControllerVC")
self.navigationController?.pushViewController(vc, animated: true)

如果我尝试将其作为单独文件中的函数运行,我得到的错误是:

使用未解析的标识符“navigationController”;你的意思是“UINavigationController”吗?

所以我想创建和调用的函数是这样的:

showVC("ExamplesControllerVC")

有什么想法吗?

【问题讨论】:

    标签: swift uinavigationcontroller pushviewcontroller


    【解决方案1】:

    此代码所在的任何函数都需要更新以获取UIViewController 类型的参数。

    func showMain(on vc: UIViewController) {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: "ExamplesControllerVC")
        vc.navigationController?.pushViewController(vc, animated: true)
    }
    

    现在你可以这样称呼它:

    showMain(on: someViewController)
    

    或者将此函数添加到UIViewController 的扩展中,那么您对self 的使用就可以了。

    extension UIViewController {
        func showMain() {
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let vc = storyboard.instantiateViewController(withIdentifier: "ExamplesControllerVC")
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    

    【讨论】:

      【解决方案2】:

      你想做这样的事情吗?:

      extension UIViewController {
          func presentView(withIdentifier: String) {
              if let newVC = self.storyboard?.instantiateViewController(withIdentifier: withIdentifier) {
              self.present(newVC, animated: true, completion: nil)
              }
          }
      }
      

      你可以这样称呼它:

      self.presentView(withIdentifier: "yourIdentifier")
      

      【讨论】:

      • 真是聪明,没想到要用扩展。感谢您的解释。
      • 这个扩展没问题,但是有一个问题,它只有在你只使用一个故事板时才能工作。您可以在方法名称中添加SB名称参数,然后实例化SBlet sb: UIStoryboard = UIStoryboard(name: <<SB NAME PARAMETER>>, bundle: nil),只需将self.storyboard替换为sb就可以了,如果不再需要了
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-28
      • 2019-09-26
      • 1970-01-01
      • 2014-07-29
      • 2018-11-06
      • 1970-01-01
      • 2021-11-24
      相关资源
      最近更新 更多