说明
我正在定义一个通用API方法来处理应用程序中的弹出窗口。是否可以将UIViewController的类型传递给函数,然后将函数中的变量popOverVC类型转换为popUpVC的类型,即作为参数传递给函数。Swift下的所有程序都是值得的
参考代码
func showAsPopUp(currentVC: UIViewController,currentVCname: String, popupStoryboardID: String, popUpVC:UIViewController){
let popUpVCType:AnyClass = type(of: popUpVC)
let popOverVC = UIStoryboard(name: currentVCname, bundle: nil).instantiateInitialViewController(popupStoryboardID) as! popUpVCType
currentVC.addChildViewController(popOverVC)
}
这是使用泛型的好情况。
func showAsPopUp<T: UIViewController>(currentVC: UIViewController,currentVCname: String, popupStoryboardID: String, popUpVC: T.type) {
let popOverVC = UIStoryboard(name: currentVCname, bundle: nil).instantiateViewController(withIdentifier: popupStoryboardID) as! T
currentVC.addChildViewController(popOverVC)
}
不确定这里的功能是什么,但这就是泛型如何适合上述代码。
上面方法的用法如下:
showAsPopUp(currentVC: UIViewController(), currentVCname: "asdsadv", popupStoryboardID: "asd", popUpVC: SomePopUpViewController.self)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句