【问题标题】:Swift: is it possible to use generic and storyboard for UIViewControllerSwift:是否可以为 UIViewController 使用通用和故事板
【发布时间】:2014-07-08 13:44:33
【问题描述】:

假设,我有 UIViewController 子类:

class InformationServiceMenuVC <T : InformationServiceItemProtocol>: UITableViewController {

}

通常我可以通过调用类似的方法来创建视图控制器的实例:

let vc = InformationServiceSideMenuVC<InformationServiceMenuItem>()

但是在使用情节提要时如何传递所需的泛型类型?

【问题讨论】:

  • 您是否尝试将情节提要中的课程设置为InformationServiceSideMenuVC&lt;InformationServiceMenuItem&gt;
  • 是的,它说未知类并初始化 UITableViewController 实例

标签: xcode swift generics


【解决方案1】:

创建一个继承自泛型类的具体类:

class SpecificInformationServiceMenuVC : InformationServiceMenuVC<Specific> {}

然后您可以使用特定的子类作为您在故事板中的类类型。

甚至可以只创建一个类型别名:

typealias SpecificInformationServiceMenuVC = InformationServiceMenuVC<Specific>

【讨论】:

  • 继承不会编译,因为派生类也必须是泛型的。 typealias 将完成这项工作
  • 嗯...很不幸,这似乎是一种相当普遍的做法。
  • 我尝试过使用类型别名,但从 Xcode 6.1 开始也不起作用。我认为这是一个错误,您不能在情节提要中使用泛型类或类型别名。
【解决方案2】:

在 Swift 3.0.1 中,我能够由此重构:

class TagPickerViewController: BaseViewController, HasAppController {
}
extension TagPickerViewController: UITableViewDelegate {
}

到:

class TagPickerViewControllerGeneric<TagViewModelClass: TagPickerViewModel>
    : BaseViewController {
}
class TagPickerViewController: TagPickerViewControllerGeneric<TagPickerViewModel>, 
    HasAppController, UITableViewDelegate {
}

同时将TagPickerViewController 保留在storyboard/xib 中。希望对你有帮助

【讨论】:

    猜你喜欢
    • 2013-10-25
    • 2019-11-22
    • 2023-03-05
    • 2014-03-19
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多