【问题标题】:Create a function that takes a UIViewController as a parameter创建一个以 UIViewController 作为参数的函数
【发布时间】:2018-06-18 21:17:56
【问题描述】:

我正在尝试创建一个将 UIViewController 作为函数的函数。这样做的原因是可以传递多个自定义视图控制器。这是我当前的函数,它可以工作,但使用 switch 语句和枚举:

enum controllerTypes {
    case First, Second
}

extension UIViewController {

    func presentViewController(storyBoardName: String, storyBoardIdentifier: String, controllerType: controllerTypes, completion:(() -> Void)?) {

        switch controllerType {

        case .First:
            let firstVC = UIStoryboard(name: storyBoardName, bundle: nil).instantiateViewController(withIdentifier: storyBoardIdentifier) as? FirstViewController
            if let firVC = firstVC {
                self.present(firVC, animated: true, completion: nil)
            }
        case .Second:
            let secondVC = UIStoryboard(name: storyBoardName, bundle: nil).instantiateViewController(withIdentifier: storyBoardIdentifier) as? SecondViewController
            if let secVC = secondVC {
                self.present(secVC, animated: true, completion: nil)
            }
        }
        completion?()
    }
}

我没有为参数传递“controllerTypes”枚举,而是将任何类型的 UIViewController 传递给它,当我尝试执行此操作时,出现以下错误:

        func presentViewController(storyBoardName: String, storyBoardIdentifier: String, controllerType: UIViewController, completion:(() -> Void)?) {
            let sampleVC = UIStoryboard(name: storyBoardName, bundle: nil).instantiateViewController(withIdentifier: storyBoardIdentifier) as? controllerType//error - use of undeclared type 'controllerType'
            if let samVC = sampleVC {
                self.present(samVC, animated: true, completion: nil)
            }
}

知道是否可以这样做吗?

【问题讨论】:

  • 你是根据VC的类型来赋值还是直接存在?
  • @Sh_Khan 到目前为止它刚刚呈现
  • 我希望使用一个参数来接受它将呈现的 UIViewController

标签: ios swift uiviewcontroller presentviewcontroller


【解决方案1】:

你必须使你的函数泛型,然后转换为泛型参数类型:

extension UIViewController {
    func presentViewController<T: UIViewController>(storyBoardName: String, storyBoardIdentifier: String, controllerType: T.Type, completion:(() -> Void)?) {
        let sampleVC = UIStoryboard(name: storyBoardName, bundle: nil).instantiateViewController(withIdentifier: storyBoardIdentifier) as? T
        if let samVC = sampleVC {
            self.present(samVC, animated: true, completion: completion)
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-22
    • 2022-08-17
    • 2023-04-06
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    相关资源
    最近更新 更多