swift - 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")
有任何想法吗?
解决方案
无论此代码的功能是什么,都需要更新以获取 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)
}
}
推荐阅读
- python - 那是什么类型的错误?
- excel - 连接区域中的行和区域中的列
- json - 将列表转换为 Groovy 中的地图列表
- raspberry-pi - 树莓派 pico usb 在 Windows 上调试
- javascript - 如何解决/修复此问题 throw new TypeError('app.use() requires a middleware function') 在节点 js 中启动服务器时
- python - 使用python从json中提取csfr令牌
- express - 减少我的 Express 应用程序的代码大小
- flutter - 颤振 | 获取 Firebase 电子邮件链接登录数据
- selenium - 如何在机器人框架中忽略全局导入中的导入文件
- python - 创建一个只提取行的新数据框包含一个特定的单词