我有以下用例。 我正在使用KYDrawerController库。我做了一个抽屉菜单,它工作得很好。我的MainViewController是一个UINavigationController。在工具栏/导航栏上,我有一个汉堡图标打开抽屉菜单。 抽屉菜单包含项目,当用户点击它时,它应该打开一个屏幕。
在Android中,当选择一个项目时,会使用片段替换内容,在这种情况下,工具栏会保留汉堡包图标,抽屉控制器仍然可以轻松打开。
我如何在Swift上实现它,使用UINavigationController是一个好主意还是有更好的选择。要求如下。
最佳解决方案是什么?有人有一个代码示例。
答案 0 :(得分:1)
根据代码,他们已经在使用UINavigationController来加载所选的菜单选项。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)newIndexPath{
[tableView deselectRowAtIndexPath:newIndexPath animated:YES];
KYDrawerController *elDrawer = (KYDrawerController*)self.navigationController.parentViewController;
UIViewController *viewController;
switch ([newIndexPath row]) {
case 0:{
viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"VC1"];
break;
}
case 1:{
viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"VC2"]; break;
}
default:{
viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"VC3"];
break;
}
}
UINavigationController *navController=[[UINavigationController alloc]initWithRootViewController:viewController];
elDrawer.mainViewController=navController;
[elDrawer setDrawerState:DrawerStateClosed animated:YES];
}
要从侧边菜单加载的控制器,您需要添加一个左栏按钮作为抽屉按钮。在该按钮的选择器中,您需要添加以下代码行。
- (IBAction)clickedOpen:(id)sender {
KYDrawerController *elDrawer = (KYDrawerController*)self.navigationController.parentViewController;
[elDrawer setDrawerState:DrawerStateOpened animated:YES];
}
答案 1 :(得分:1)
首先,您应该设置KYDrawerController
以使其成为应用程序的根视图控制器,我建议将drawerController
声明为AppDelegate.swift
中的实例变量:< / p>
var drawerController:KYDrawerController?
因此,在didFinishLaunchingWithOptions
方法中,您可以实现:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
// let's say that you got your first view controller from the "Main" storyboard:
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
// asssume that controller would be "HomeViewController"
let homeVC = mainStoryboard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
let navigation:UINavigationController = UINavigationController(rootViewController: homeVC)
appDelegate.drawerController = KYDrawerController(drawerDirection: .left , drawerWidth: 280)
appDelegate.drawerController.mainViewController = navigation
appDelegate.window?.rootViewController = appDelegate.drawerController
通过实施上述代码,您应该能够在应用中更改要从anywhere
打开的抽屉的状态,如下所示:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.drawerController!.setDrawerState(.opened, animated: true)