首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UIStoryboard扩展

UIStoryboard扩展
EN

Stack Overflow用户
提问于 2016-04-16 13:36:51
回答 1查看 1.1K关注 0票数 0

为了更安全地实例化视图控制器,我正在尝试创建一个快速的故事板扩展

代码语言:javascript
复制
protocol IdentifierType {
     typealias Identifier: RawRepresentable
}

extension IdentifierType where Self: UIStoryboard, Identifier.RawValue == String  {

    func instantiateViewControllerWithIdentifier(identifier:Identifier) -> UIViewController {
        return self.instantiateViewControllerWithIdentifier(identifier.rawValue)
    }

}

而且它不会在编译时出错。但是,当我试图实现它时,应该这样:

代码语言:javascript
复制
extension UIStoryboard : IdentifierType {
    enum Identifier: String {
        case MainViewController = "MAIN_VIEW_CONTROLLER"
        case ContactUsViewController = "CONTACT_US_VIEW_CONTROLLER"
        case AboutViewController = "ABOUT_VIEW_CONTROLLER"
    }
}

出现编译时错误。“在此上下文中,”标识符“对于类型查找是不稳定的”

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-16 20:17:30

你可以这样说:

代码语言:javascript
复制
protocol IdentifierType {
    associatedtype Identifier: RawRepresentable
}

extension UIStoryboard : IdentifierType {
    enum Identifier: String {
        case MainViewController = "MAIN_VIEW_CONTROLLER"
        case ContactUsViewController = "CONTACT_US_VIEW_CONTROLLER"
        case AboutViewController = "ABOUT_VIEW_CONTROLLER"
    }

    func instantiateViewControllerWithIdentifier(identifier:Identifier) -> UIViewController {
        return self.instantiateViewControllerWithIdentifier(identifier.rawValue)
    }
}

然后,您可以调用类似于self.storyboard?.instantiateViewControllerWithIdentifier(.ContactUsViewController)的东西,这正是您想要的。

不确定在这种情况下拥有RawRepresentable的好处是什么,也许您可以解释为什么您认为需要使用它。

但假设这是您所需要的一切,协议IdentifierType是完全不必要的,因此可以简化为:

代码语言:javascript
复制
extension UIStoryboard  {
    enum Identifier: String {
        case MainViewController = "MAIN_VIEW_CONTROLLER"
        case ContactUsViewController = "CONTACT_US_VIEW_CONTROLLER"
        case AboutViewController = "ABOUT_VIEW_CONTROLLER"
    }

    func instantiateViewControllerWithIdentifier(identifier:Identifier) -> UIViewController {
        return self.instantiateViewControllerWithIdentifier(identifier.rawValue)
    }
}

您可以在这里这里。中找到关于删除带有枚举的硬编码字符串的讨论。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36664870

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档