如何使用 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

ios - 从 View  Controller 到 View  Controller 的泛型函数转移-LMLPHP

最佳答案

如下更改方法签名,指定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/

10-08 20:53