xcode 将viewController作为参数传入函数

vwhgwdsa  于 2023-01-18  发布在  其他
关注(0)|答案(2)|浏览(133)

我想将viewController类型作为函数传递,就像下面的代码一样

extension UIViewController {
    func switchScreen(storyboardName:String,viewControllerName:String,vcc:UIViewController) {
        let mainStoryboard = UIStoryboard(name: storyboardName, bundle: Bundle.main)
        if let viewController = mainStoryboard.instantiateViewController(withIdentifier: viewControllerName) as? vcc {
            self.present(viewController, animated: true, completion: nil)
        }
    }
}

但是xcode返回了错误Cannot find type 'vcc' in scope
我试着在UIViewController后面的参数中添加.Type,但错误是相同的。有解决方法吗?

woobm2wo

woobm2wo1#

第三个参数必须是类型,而不是示例

extension UIViewController {
    func switchScreen<T : UIViewController>(storyboardName: String, viewControllerName: String, type: T.Type) {
        let mainStoryboard = UIStoryboard(name: storyboardName, bundle: Bundle.main)
        if let viewController = mainStoryboard.instantiateViewController(withIdentifier: viewControllerName) as? T {
            self.present(viewController, animated: true, completion: nil)
        }
    }
}

并称之为

switchScreen(storyboardName: "Main", 
             viewControllerName: "Foo", 
             type: LoginViewController.self)

但是由于instantiateViewControllerpresent不关心静态类型,因此您不需要它,这就足够了

extension UIViewController {
    func switchScreen(storyboardName: String, viewControllerName: String) {
        let mainStoryboard = UIStoryboard(name: storyboardName, bundle: Bundle.main)
        let viewController = mainStoryboard.instantiateViewController(withIdentifier: viewControllerName)
        self.present(viewController, animated: true, completion: nil)
    }
}

为了避免崩溃,您可以添加一个具有可用视图控制器标识符的枚举,并在第二个参数中传递此类型,例如

enum ControllerIdentifier : String, RawRepresentable {
    case foo, bar
}

extension UIViewController {
    func switchScreen(storyboardName: String, viewControllerName: ControllerIdentifier) {
        let mainStoryboard = UIStoryboard(name: storyboardName, bundle: Bundle.main)
        let viewController = mainStoryboard.instantiateViewController(withIdentifier: viewControllerName.rawValue)
        self.present(viewController, animated: true, completion: nil)
    }
}
qltillow

qltillow2#

使用通用参数

extension UIViewController {
    func switchScreen<T: UIViewController>(storyboardName:String,viewControllerName:String,vcc:T) {
        let mainStoryboard = UIStoryboard(name: storyboardName, bundle: Bundle.main)
        if let viewController = mainStoryboard.instantiateViewController(withIdentifier: viewControllerName) as? T {
            self.present(viewController, animated: true, completion: nil)
        }
    }
}

相关问题