ios - 调用通用控制器
问题描述
我的课程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
。
解决方案
您可以通过使用协议来完成此操作。定义一些需要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)
推荐阅读
- java - 仅在临界区中断另一个线程
- mediawiki - DrawioEditor 扩展似乎在 MediaWiki 1.33 中不起作用
- excel - 将 excel 文件转换为 .txt 文件时如何删除尾随制表符和引号?
- java - @Around 注释:使变量可用于连接点而不更改方法签名并稍后使用
- ansible - 添加选项以仅在 var 定义时进行同步
- sql - 如何重构在 SQL Server 中具有联接的子查询
- microsoft-graph-api - msgraph-sdk-dotnet:为 Post/Put/Patch 请求获取 HttpRequestMessage
- aws-lambda - 触发 lambda cloudwatch vs api 网关
- regex - 为什么下划线会像 python 3 re 库中的通配符一样匹配
- android - 如何修复突然的通用 Gradle Project Sync Failed 错误