導航欄 UINavigation

UINavigation

系統默認從上一個ViewController跳轉到下一個ViewController時,backItem 是 < + 上ViewController的Navigation title這樣的,如


backItem.png

但項目可能會被要求所有的Vc界面的返回按鈕為

backItemCustom.png

這時我們可以改寫系統的PushViewController方法,在頁面被Push過去時,將BackItem換成我們自己定義的item。

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if (self.viewControllers.count > 0)
    {
        viewController.hidesBottomBarWhenPushed = YES;
        // 設置下一頁面的返回鍵
        UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
        but.frame = CGRectMake(0, 0, 50, 20);
        [but setImage:[UIImage imageNamed:@"nav_back_black.png"] forState:UIControlStateNormal];
        [but setTitle:@"<返回" forState:UIControlStateNormal];
        but.userInteractionEnabled = YES;
        [but addTarget:self action:@selector(toBack) forControlEvents:UIControlEventTouchUpInside];
        viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:but];
    }
    [super pushViewController:viewController animated:animated];
}
- (void)toBack
{
    [self popViewControllerAnimated:YES];
}

在我們自己寫的toBack方法里面調用系統的popViewControllerAnimated方法,這樣就實現了所有的頁面都是統一的返回風格。

UIBarButtonItem初始化方法中提供了
- (instancetype)initWithTitle:(nullable NSString *)title style:(UIBarButtonItemStyle)style target:(nullable id)target action:(nullable SEL)action;
我們用自己寫好的selctor去替換到系統的rightBarButtonItem,那么就可以實現將我們自己想要的東西添加到導航欄上

        self.navigationItem.rightBarButtonItem = item; ```

在toNext方法中實現我們自己的操作
  • (void)toNext
    {
    // 自己的實現
    };
如下圖,點擊“完成”后就會pop回上一頁

![customItem.png](http://upload-images.jianshu.io/upload_images/3141335-660bb839711b436f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


同理可以修改leftBarButtonItem 和 隱藏返回鍵。
https://github.com/hardy88/HTStudy/tree/master/iOS學習/HTHXBB
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容