Swift: 不能在函数内部使用 navigationController.pushViewController

Swift: Can't use navigationController.pushViewController inside a function

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

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

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

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

Use of unresolved identifier 'navigationController'; did you mean 'UINavigationController'?

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

showVC("ExamplesControllerVC")

有什么想法吗?

此代码中的任何函数都需要更新以采用 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)
    }
}

你想做这样的事情吗?:

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")