如何使用 func as? ViewController
输入数据?
private func toVC<T>(_ id: String, vc: T.Type) {
if let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: id) as? T {
if let window = self.window, let rootVC = window.rootViewController {
var currVC = rootVC
let navVC = UINavigationController()
while let presentVC = currVC.presentedViewController {
currVC = presentVC
}
navVC.viewControllers = [vc]
currVC.present(navVC, animated: true, completion: nil)
}
}
}
我在
Cannot convert value of type 'T' to expected element type 'UIViewController'
中收到错误navVC.viewControllers = [vc]
。如何正确创建功能?
UPD
最佳答案
如下更改方法签名,指定T
类型的UIViewController
,
private func toVC<T: UIViewController>(_ id: String, vc: T.Type) {
要为特定控制器传递
data
,private func toVC<T>(_ id: String, vc: T.Type, data: Any) {
if let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: id) as? T {
if let window = self.window, let rootVC = window.rootViewController {
var currVC = rootVC
let navVC = UINavigationController()
while let presentVC = currVC.presentedViewController {
currVC = presentVC
}
(vc as? MyViewController1)?.data = data
(vc as? MyViewController2)?.data = data
navVC.viewControllers = [vc]
currVC.present(navVC, animated: true, completion: nil)
}
}
}
关于ios - 从 View Controller 到 View Controller 的泛型函数转移,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58280286/