您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

用 AMSlideMenu 實作 iOS 左右側滑(抽屜式)菜單

編輯:iOS 相關資訊

側滑抽屜菜單是相當常見的導覽模式。這裡示範以開源元件 AMSlideMenu 實作,它同時支援只開左側、只開右側,或左右皆可,並且相容 Storyboard 與 xib 兩種開發方式。以下說明 xib 版本的做法。

步驟一:安裝元件

在 Podfile 中加入:

pod "AMSlideMenu", "~> 1.5.3"

然後執行 pod install 匯入專案。

步驟二:在 pch 中關閉 Storyboard 模式

請注意要改的是 Pods 專案(不是你自己的專案)裡的 Pods-*.pch:

// 必須加上,否則 xib 方式會報錯
#define AMSlideMenuWithoutStoryboards

步驟三:建立主控制器

讓主視圖控制器繼承 AMSlideMenuMainViewController,並在 viewDidLoad 中指定左右菜單:

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

    [super viewDidLoad];
}

// 設定左側菜單按鈕樣式(右側寫法相同)
- (void)configureLeftMenuButton:(UIButton *)button
{
    CGRect frame = button.frame;
    frame.origin = (CGPoint){0, 0};
    frame.size   = (CGSize){40, 40};
    button.frame = frame;
}

這裡有個容易忽略的細節:初始化左右菜單的程式碼要放在 [super viewDidLoad] 之前,因為父類別會在載入時讀取這兩個屬性。

步驟四:建立側邊菜單列表

讓菜單類繼承 AMSlideMenuLeftTableViewController(右側則繼承 AMSlideMenuRightTableViewController):

- (void)viewDidLoad
{
    [super viewDidLoad];

    // 初始化菜單項
    self.tableData = [@[@"VC 1", @"VC 2", @"VC 3"] mutableCopy];
}

// 點擊菜單項切換內容頁
- (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];
}

關鍵是 openContentNavigationController:,它把選到的控制器換成主要內容,同時自動收起抽屜。

步驟五:在 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;
}

完成以上五步,左右抽屜菜單就能運作。若要調整菜單寬度、開關動畫或背景遮罩,AMSlideMenuMainViewController 另外提供了多組可覆寫的方法,可以依需求微調。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved