从视图控制器到视图控制器的通用函数传输
Generic func transfer from view controller to view controller
如何在 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)
}
}
}
我在 navVC.viewControllers = [vc]
中收到错误 Cannot convert value of type 'T' to expected element type 'UIViewController'
。
如何正确创建函数?
UPD
更改方法签名如下,指定类型 UIViewController
、
的 T
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)
}
}
}
如何在 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)
}
}
}
我在 navVC.viewControllers = [vc]
中收到错误 Cannot convert value of type 'T' to expected element type 'UIViewController'
。
如何正确创建函数?
UPD
更改方法签名如下,指定类型 UIViewController
、
T
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)
}
}
}