使用Swift在switch / case语句中设置UIViewController

时间:2018-03-14 12:11:39

标签: swift xcode uiviewcontroller

我正在尝试根据按下按钮加载视图。我想我可以做下面的事情,我定义了一个通用的UIViewController,然后将它设置为switch / case语句中的特定UIViewController,但它显然不会以这种方式工作。我做错了什么?

@objc func menuButton(sender: UIButton) {
    var view: UIViewController!
    switch sender.tag {
        case 0:
            view = MenuViewController()
            view.menuType = .Account
        case 1:
            view = MenuViewController()
            view.menuType = .Sync
        case 2:
            view = AuthViewController()
            view.menuType = .Auth
        default: break
    }
    self.navigationController?.pushViewController(view, animated: true)
}

1 个答案:

答案 0 :(得分:1)

如果我没弄错的话,编译器应该输错:

  

'UIViewController'类型的值没有成员'menuType'

这里有几个选项可以解决这个问题:

解决方案1 ​​

使用cast

@objc func menuButton(sender: UIButton) {
    var view: UIViewController!
    switch sender.tag {
        case 0:
            view = MenuViewController()
            (view as? MenuViewController())?.menuType = .Account
        case 1:
            view = MenuViewController()
            (view as? MenuViewController())?.menuType = .Sync
        case 2:
            view = AuthViewController()
            (view as? AuthViewController())?.menuType = .Auth
        default: break
    }
    self.navigationController?.pushViewController(view, animated: true)
}

解决方案2

创建协议MenuProtocol

protocol MenuProtocol {
    var menuType: MenuType { get set }
}

并使MenuViewControllerAuthViewController实现该协议。然后,您可以执行以下操作:

@objc func menuButton(sender: UIButton) {
    var view: (UIViewController & MenuProtocol)!
    switch sender.tag {
        case 0:
            view = MenuViewController()
            view.menuType = .Account
        case 1:
            view = MenuViewController()
            view.menuType = .Sync
        case 2:
            view = AuthViewController()
            view.menuType = .Auth
        default: break
    }
    self.navigationController?.pushViewController(view, animated: true)
}