ios - 如何将 UIViewController 类型传递给函数并在 iOS Swift 中类型转换变量?

标签 ios swift uiviewcontroller casting

解释

我正在定义一个通用 API 方法来处理我的应用程序中的弹出窗口。是否可以将 UIViewController 的类型传递给函数并将函数中的变量 popOverVC 类型转换为 popUpVC 的类型,即作为参数传递给函数。 Swift下的所有程序都可观

引用代码

func showAsPopUp(currentVC: UIViewController,currentVCname: String, popupStoryboardID: String, popUpVC:UIViewController){
        let popUpVCType:AnyClass = type(of: popUpVC)
        let popOverVC = UIStoryboard(name: currentVCname, bundle: nil).instantiateInitialViewController(popupStoryboardID) as! popUpVCType
        currentVC.addChildViewController(popOverVC)
    }

最佳答案

这是使用 generics 的好情况.

func showAsPopUp<T: UIViewController>(currentVC: UIViewController,currentVCname: String, popupStoryboardID: String, popUpVC: T.type) {
    let popOverVC = UIStoryboard(name: currentVCname, bundle: nil).instantiateViewController(withIdentifier: popupStoryboardID) as! T
    currentVC.addChildViewController(popOverVC)
}

不确定您的功能是什么,但这就是泛型与上述代码相适应的方式。

上述方法的用法如下:

showAsPopUp(currentVC: UIViewController(), currentVCname: "asdsadv", popupStoryboardID: "asd", popUpVC: SomePopUpViewController.self)

关于ios - 如何将 UIViewController 类型传递给函数并在 iOS Swift 中类型转换变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48594536/

相关文章:

ios - 以编程方式更改 Y 位置约束

ios - 找不到接口(interface)声明和尝试使用转发类错误

ios - 计算 UIView 的内容大小?

ios - 如何理解 table.autoresizingMask 的行为?

ios - 将 AVPlayerLayer 添加到 UIViewController

iOS 11 : Height of UINavigationBar for large title (mimic Apple Music App)

iOS:在 pod 中使用 Segment-Firebase 时构建 Xcode 项目时出错

swift - 如何比较文本字段内的文本字段值?

ios - AudioKit 5 和 Xcode 12 beta 6 构建错误

ios - 在 ViewController 和 TabBarController 之间传递数据