在 iOS 中,UINavigationController 負責管理視圖堆疊。最常見的操作包括 push、pop、popToViewController 與 popToRootViewController。
[self.navigationController pushViewController:commentListVC animated:YES];
[self.navigationController popViewControllerAnimated:YES];
[self.navigationController popToRootViewControllerAnimated:YES];若不希望返回按鈕顯示上一頁標題,可以自訂 backBarButtonItem,把文字設為空字串,讓返回箭頭更簡潔。
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:nil action:NULL];導覽列左右两侧都可以放自訂 UIBarButtonItem。常見做法是用 UIButton 建立項目,再包成 BarButtonItem。
UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
UIBarButtonItem *bar1 = [[UIBarButtonItem alloc] initWithCustomView:btn1];
self.navigationItem.leftBarButtonItem = bar1;若需要多個項目,也可以使用陣列一次設定。
self.navigationItem.leftBarButtonItems = @[bar1, bar2];navigationItem.titleView 可以放自訂 view,例如 label 或搜尋框。若要調整返回箭頭顏色,可設定 navigationBar 的 tintColor。若要改標題文字樣式,則可透過 titleTextAttributes 設定。
某些頁面需要全螢幕呈現,可以隱藏 navigationBar。
self.navigationController.navigationBarHidden = YES;掌握 push 與 pop 系列方法,再加上左右導覽項、標題樣式與隱藏設定,就能應付大部分導覽列客製需求。