gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 06:25:47 26 4
gpt4 key购买 nike

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

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

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

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

关于Swift:不能在函数内使用 navigationController.pushViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55128488/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com