首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >返回以下内容的通用方法: UIViewController、UINavigationController、UITabController

返回以下内容的通用方法: UIViewController、UINavigationController、UITabController
EN

Stack Overflow用户
提问于 2017-11-12 12:08:49
回答 1查看 100关注 0票数 2

我的应用程序可以动态地更改AppBaseController (登录后显示)。它可以有以下几点:

菜单控制器( UIViewController)、UINavigationController或UITabBarController

我正在用工厂创建这个控制器,并希望工厂遵循如下协议:

代码语言:javascript
复制
protocol MainRootApplication {
    func create() -> UIViewController
}

工厂确认的两个示例:(使用AutoInject Swinject进行依赖项注入)

代码语言:javascript
复制
class MenuControllerFactory: Factory,MainRootApplication {
    func create() -> MenuController {
        self.container.autoregister(MenuController.self, initializer: MenuController.init)
        return self.container.resolve(MenuController.self)!
    }
}

class MainTabBarControllerFactory: Factory, MainRootApplication {
    func create() -> MainTabBarController {
        self.container.autoregister(MainTabBarController.self, initializer: MainTabBarController.init)
        return self.container.resolve(MainTabBarController.self)!
    }
}

正如您所看到的,这是无法完成的,因为"MainTabBarController“不是UIViewController类型的。

在没有强制铸造的情况下就能做到这一点吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-12 12:36:24

或者用一种关联类型?

代码语言:javascript
复制
protocol MainRootApplication {
    associatedtype ControllerType: UIViewController
    func create() -> ControllerType
}

然后你的工厂就会像:

代码语言:javascript
复制
class MenuControllerFactory: Factory,MainRootApplication {
    typealias ControllerType = MenuController
    func create() -> MenuController {
        self.container.autoregister(MenuController.self, initializer: MenuController.init)
        return self.container.resolve(MenuController.self)!
    }
}

class MainTabBarControllerFactory: Factory, MainRootApplication {
    typealias ControllerType = MainTabBarController
    func create() -> MainTabBarController {
        self.container.autoregister(MainTabBarController.self, initializer: MainTabBarController.init)
        return self.container.resolve(MainTabBarController.self)!
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47248599

复制
相关文章

相似问题

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