iOS:制作左右侧滑(抽屉式)菜单

感谢控件作者:https://github.com/SocialObjects-Software/AMSlideMenu

首先上效果图:


这里我们使用AMSlideMenu来实现左右侧滑菜单的效果。控件支持单独左侧滑、单独右侧滑和左右侧滑。同时支持Storyboard和xib两种开发模式。这里介绍第二种,在xib中的开发。
开发步骤如下:
1.    在Podfile中添加:pod "AMSlideMenu", "~> 1.5.3",通过pod install导入项目。
2.    在Pods项目中(注意:不是你自己的项目),在Pods-*.pch文件中添加如下一行代码:

// 必须,否则xib方式会报错
#define AMSlideMenuWithoutStoryboards

3.    实现一个继承了AMSlideMenuMainViewController类的ViewController。主要代码如下:

- (void)viewDidLoad
{
   /*******************************
    *     初始化菜单
    *******************************/
    self.leftMenu = [[LeftMenuTVC alloc] initWithNibName:@"LeftMenuTVC" bundle:nil];
    self.rightMenu = [[RightMenuTVC alloc] initWithNibName:@"RightMenuTVC" bundle:nil];
   /*******************************
    *     结束初始化
    *******************************/

    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

// 设置左侧菜单按钮样式(右侧按钮类似操作)
- (void)configureLeftMenuButton:(UIButton *)button
{
    CGRect frame = button.frame;
    frame.origin = (CGPoint){0,0};
    frame.size = (CGSize){40,40};
    button.frame = frame;
    
    [button setImage:[UIImage imageNamed:@"icon-menu.png"] forState:UIControlStateNormal];
}

4.    实现一个继承了AMSlideMenuLeftTableViewController的UITableViewController的类作为左侧菜单(右侧菜单类似)
主要代码如下:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // 初始化菜单项
    self.tableData = [@[@"VC 1",@"VC 2",@"VC 3"] mutableCopy];
}

// 点击菜单项跳转到不同的VC
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UINavigationController *nvc;
    UIViewController *rootVC;
    switch (indexPath.row) {
        case 0:
        {
            rootVC = [[FirstVC alloc] initWithNibName:@"FirstVC" bundle:nil];
        }
            break;
        case 1:
        {
            rootVC = [[SecondVC alloc] initWithNibName:@"SecondVC" bundle:nil];
        }
            break;
        case 2:
        {
            rootVC = [[ThirdVC alloc] initWithNibName:@"ThirdVC" bundle:nil];
        }
            break;
        
        default:
            break;
    }
    nvc = [[UINavigationController alloc] initWithRootViewController:rootVC];
    
    [self openContentNavigationController:nvc];
}

5.    最后记得在AppDelegate中要做这步操作(当然,其它地方也可以):

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    MainVC *mainVC = [[MainVC alloc] init];

    UINavigationController *startNVC = [[UINavigationController alloc] initWithRootViewController:mainVC];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    self.window.rootViewController = startNVC;
    [self.window makeKeyAndVisible];
    
    return YES;
}


有不明白的地方可以直接下载源码。源码地址:https://files.cnblogs.com/ilovewindy/AMSlideMenu.zip

posted @ 2014-09-24 11:48  GreatK  阅读(9749)  评论(0编辑  收藏  举报