首页 > 解决方案 > 调用通用控制器

问题描述

我的课程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”初始化中定义它,这样我就可以将该信息传递给 Menu 类 showMenu 函数,我将从那里回调调用 ViewController 中的函数?

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

标签: iosswiftgenerics

解决方案


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

protocol ActionNavigatable: UIViewController {

  func navigate(to action: Action)
}

...

final class HomeController: UIViewController, ActionNavigatable {

  func navigate(to action: Action) {

  }

...

现在在您的Menu班级中,您可以将 acontroller称为ActionNavigatable

或者,作为一个选项,您可以强制转换它:

(controller as? ActionNavigatable)?.navigate(to: action)

推荐阅读