首页 > 解决方案 > 如何在函数参数中传递视图控制器名称?

问题描述

func showalertOkayButton(message: String?, identifier: string?, viewControllerName: UIViewController){

    let alertController = UIAlertController(title: kMessage, message: message, preferredStyle: .alert)
       let defaultaction = UIAlertAction(title: kOkay, style: UIAlertAction.Style.default, handler:{ defaultaction in
        let VC = UIStoryboard(name: kMainStoryBoard, bundle: nil).instantiateViewController(withIdentifier: identifier) as! viewControllerName
        self.navigationController?.pushViewController(VC, animated: true)
    })
    alertController.addAction(defaultaction)
    present(alertController, animated: true, completion: nil)
}

所以我的问题是我无法发送viewControllerName它给我的错误“未声明的使用”所以我如何在函数中发送视图控制器名称。好吧,这是为了学习目的,如果我问错了,对不起。所以请指导我或帮助我感谢advacne。

标签: iosswiftfunctionalert

解决方案


您误解了如何as工作。在x as! y中,y 不是名称而是类型。当你有viewControllerName: UIViewController一个函数参数时,那不是传递一个传递UIViewController类型实例的名称。因此,如果要指定要转换的内容,则需要将类型作为函数参数传递。使用泛型,看起来像这样:as

func showalertOkayButton<T: UIViewController>(message: String?, identifier: String, viewControllerType: T.Type) {
    let alertController = UIAlertController(title: kMessage, message: message, preferredStyle: .alert)

    let defaultaction = UIAlertAction(title: kOkay, style: UIAlertAction.Style.default, handler:{ defaultaction in
        let VC = UIStoryboard(name: kMainStoryBoard, bundle: nil).instantiateViewController(withIdentifier: identifier) as! T
        self.navigationController?.pushViewController(VC, animated: true)
    })

    alertController.addAction(defaultaction)
    present(alertController, animated: true, completion: nil)
}

调用它看起来像这样

showalertOkayButton("Message", "VCIdentifier", MyViewController.self)

但是,在您的特定情况下,这些都不是必需的。Swift 是一种动态语言,因此当您从情节提要中实例化视图控制器时,它可以在运行时加载其动态类型信息。但是编译器不知道它是什么类型,因此它会为您提供一个简单的UIViewController实例。as直到您需要在该视图控制器上调用超类中不存在的特定方法时,才需要使用它UIViewController

即使您不强制转换它,由于多态性,它也会继续正确运行。所以你可以把你的代码缩短到这个

func showalertOkayButton(message: String?, identifier: String) {
    let alertController = UIAlertController(title: kMessage, message: message, preferredStyle: .alert)

    let defaultaction = UIAlertAction(title: kOkay, style: UIAlertAction.Style.default, handler:{ defaultaction in
        let VC = UIStoryboard(name: kMainStoryBoard, bundle: nil).instantiateViewController(withIdentifier: identifier)
        self.navigationController?.pushViewController(VC, animated: true)
    })

    alertController.addAction(defaultaction)
    present(alertController, animated: true, completion: nil)
}

推荐阅读