从视图控制器到视图控制器的泛函传递

问题描述 投票:2回答:1

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

enter image description here

ios swift xcode viewcontroller
1个回答
2
投票
如下更改更改方法签名,指定类型为TUIViewController

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) } } }

© www.soinside.com 2019 - 2024. All rights reserved.