ios - 如何在函数参数中传递视图控制器名称?
问题描述
func showalertOkayButton(message: String?, identifier: string?, viewControllerName: UIViewController){
let alertController = UIAlertController(title: kMessage, message: message, preferredStyle: .alert)
let defaultaction = UIAlertAction(title: kOkay, style: UIAlertAction.Style.default, handler:{ defaultaction in
let VC = UIStoryboard(name: kMainStoryBoard, bundle: nil).instantiateViewController(withIdentifier: identifier) as! viewControllerName
self.navigationController?.pushViewController(VC, animated: true)
})
alertController.addAction(defaultaction)
present(alertController, animated: true, completion: nil)
}
所以我的问题是我无法发送viewControllerName
它给我的错误“未声明的使用”所以我如何在函数中发送视图控制器名称。好吧,这是为了学习目的,如果我问错了,对不起。所以请指导我或帮助我感谢advacne。
解决方案
您误解了如何as
工作。在x as! y
中,y 不是名称而是类型。当你有viewControllerName: UIViewController
一个函数参数时,那不是传递一个传递UIViewController类型实例的名称。因此,如果要指定要转换的内容,则需要将类型作为函数参数传递。使用泛型,看起来像这样:as
func showalertOkayButton<T: UIViewController>(message: String?, identifier: String, viewControllerType: T.Type) {
let alertController = UIAlertController(title: kMessage, message: message, preferredStyle: .alert)
let defaultaction = UIAlertAction(title: kOkay, style: UIAlertAction.Style.default, handler:{ defaultaction in
let VC = UIStoryboard(name: kMainStoryBoard, bundle: nil).instantiateViewController(withIdentifier: identifier) as! T
self.navigationController?.pushViewController(VC, animated: true)
})
alertController.addAction(defaultaction)
present(alertController, animated: true, completion: nil)
}
调用它看起来像这样
showalertOkayButton("Message", "VCIdentifier", MyViewController.self)
但是,在您的特定情况下,这些都不是必需的。Swift 是一种动态语言,因此当您从情节提要中实例化视图控制器时,它可以在运行时加载其动态类型信息。但是编译器不知道它是什么类型,因此它会为您提供一个简单的UIViewController
实例。as
直到您需要在该视图控制器上调用超类中不存在的特定方法时,才需要使用它UIViewController
。
即使您不强制转换它,由于多态性,它也会继续正确运行。所以你可以把你的代码缩短到这个
func showalertOkayButton(message: String?, identifier: String) {
let alertController = UIAlertController(title: kMessage, message: message, preferredStyle: .alert)
let defaultaction = UIAlertAction(title: kOkay, style: UIAlertAction.Style.default, handler:{ defaultaction in
let VC = UIStoryboard(name: kMainStoryBoard, bundle: nil).instantiateViewController(withIdentifier: identifier)
self.navigationController?.pushViewController(VC, animated: true)
})
alertController.addAction(defaultaction)
present(alertController, animated: true, completion: nil)
}
推荐阅读
- java - 多维数组到缩进列表
- javascript - 在 Node 中暂停和恢复下载文件
- javascript - 在地图循环中生成多个参考
- entity-framework - 无法访问新创建对象的导航属性
- python - 如何从 .npy 文件中仅加载几行?
- python - 如果我已经将列表定义为变量,如何检查变量是否为列表类型?
- python - 如何使用 Django 和 BeautifulSoup 在 html 中呈现 IMDB 信息?
- javascript - 尝试使用 NodeJS 生成自述文件
- go - 或者 golang 模板中的语句结合 gt/lt (greaterThan, lowerThan)
- python - 为什么我的 DataFrame 没有保存到 Pandas_python 中的变量 q5