呼叫通用控制器

时间:2019-07-08 11:57:31

标签: ios swift generics

我有一个类Menu,它是'UICollectionView'。在该类中,我有一个名为showMenu()

的函数。

在显示菜单功能中,我完成了所有操作,然后需要根据操作(编辑,ShowAll等)导航到控制器。我尝试通过在类中调用控制器变量来做到这一点。像这样:self.controller.navigateToAction(action:action)

class Menu: NSObject, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    weak var controller: ViewController? //can we define this as generic?

    func showMenu(action: Action) {
      // some logic        
      // then I need to navigate to the function in the controller

      self.controller?.navigateToAction(action: action)
   }
}

在我的控制器中,我将此函数称为:(注意menu.controller = self)。请注意,我将有许多视图控制器(homecontroller,summarycontroller等)

class HomeController: UIViewController {

lazy var menuLauncher: Menu = {
        let menu = Menu()
        menu.controller = self
        menu.actions =  {
            return [
                Action(name: .Edit, imageName: "edit"),
                Action(name: .ViewAll, imageName: "view-all"),
                Action(name: .Cancel, imageName: "cancel")
            ]}()

        return menu
    }()

   func navigateToAction(action: action) {

    // based on action navigate to a certain viewcontroller(edit, viewall, etc)
    }

    // Cell delegate functions on button click    
    func launchSlider() {
         menuLauncher.showMenu()
    }
}

在Menu类中是否可以定义可以在“ menuLancher”初始化中定义的通用viewcontroller,因此可以将该信息传递给Menu类,showMenu函数,从那里我可以在调用ViewController?

我需要在调用navigateToAction中访问ViewController函数。

1 个答案:

答案 0 :(得分:0)

您可以使用协议来完成此操作。定义一些需要func navigateToAction(action: Action)方法的协议(也可以将协议约束到UIViewController)

protocol ActionNavigatable: UIViewController {

  func navigate(to action: Action)
}

...

final class HomeController: UIViewController, ActionNavigatable {

  func navigate(to action: Action) {

  }

...

现在在您的Menu类中,您可以将controller称为ActionNavigatable

或者,作为一种选择,您可以投射它:

(controller as? ActionNavigatable)?.navigate(to: action)
相关问题