如何在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) } } }