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

自訂 UINavigationController 攔截 push 設定按鈕

編輯:iOS 相關資訊

在 iOS 中,若多個頁面都需要相同的 navigation bar 按鈕,逐頁設定會造成重複程式碼。常見解法有三種:每頁各自實作、建立共同父類、或自訂 UINavigationController 攔截 push。

第一種直覺但維護成本高;第二種會與系統控制器繼承結構衝突,例如 UITableViewController 無法再繼承自訂父類;第三種彈性最高,可在 push 時統一設定左右按鈕。

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if (self.viewControllers.count > 0) {
        viewController.hidesBottomBarWhenPushed = YES;
        viewController.navigationItem.leftBarButtonItem =
            [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"]
                                             style:UIBarButtonItemStylePlain
                                            target:self
                                            action:@selector(back)];
        viewController.navigationItem.rightBarButtonItem =
            [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"more"]
                                             style:UIBarButtonItemStylePlain
                                            target:self
                                            action:@selector(more)];
    }
    [super pushViewController:viewController animated:animated];
}

- (void)back {
    [self popViewControllerAnimated:YES];
}

- (void)more {
    [self popToRootViewControllerAnimated:YES];
}

若某頁需要不同按鈕,可在該頁的 viewDidLoad 重新覆寫 navigationItem。這種做法能讓全域導覽一致,同時保留單頁客製彈性。

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