首页 > 解决方案 > Swift:不能在函数中使用 navigationController.pushViewController

问题描述

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

该代码在 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")

有任何想法吗?

标签: swiftuinavigationcontrollerpushviewcontroller

解决方案


无论此代码的功能是什么,都需要更新以获取 type 的参数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)
    }
}


推荐阅读