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

问题描述 投票:1回答:2

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

代码在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
2个回答
1
投票

你想做这样的事吗?:

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

2
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.