去掉 iOS 導航欄返回按鈕文本三種方案
作者:街角仰望
方案一:該方法會出現部分子控制器頁面的返回按鈕文字出現的bug,需要在其子控制器頁面的父控制器里再次如上設置返回按鈕才行。
本文轉載自微信公眾號「網羅開發」,作者街角仰望。轉載本文請聯系網羅開發公眾號。
方案一
- 自定義 UINavigationController
- 遵守 ``` 協議
- 實現下面方法:
- #pragma mark --------- UINavigationBarDelegate
- - (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPushItem:(UINavigationItem *)item {
- //設置導航欄返回按鈕文字
- UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithTitle:nil style:UIBarButtonItemStylePlain target:nil action:nil];
- /*
- NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
- textAttrs[UITextAttributeTextColor] = [UIColor whiteColor];
- [back setTitleTextAttributes:textAttrs forState:UIControlStateNormal];
- */
- item.backBarButtonItem = back;
- return YES;
- }
注意:該方法會出現部分子控制器頁面的返回按鈕文字出現的bug,需要在其子控制器頁面的父控制器里再次如上設置返回按鈕才行
- 子控制器頁面的父控制器
- #pragma mark -------- 生命周期函數
- - (void)viewDidLoad {
- [super viewDidLoad];
- // Do any additional setup after loading the view.
- self.view.backgroundColor = [UIColor whiteColor];
- //重新設置下級子頁面導航欄返回按鈕文字
- UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:nil style:UIBarButtonItemStylePlain target:nil action:nil];
- self.navigationItem.backBarButtonItem = item;
- }
方案二
- 自定義 UINavigationController
- 遵守
協議 - 實現下面方法:
- #pragma mark --------- UINavigationBarDelegate
- - (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPushItem:(UINavigationItem *)item {
- //設置導航欄返回按鈕文字為透明的,可能造成導航標題不居中的問題
- [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateNormal];
- [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateHighlighted];
- return YES;
- }
方案三(推薦)
- 給 UIViewController 添加類別(這里的類別不需要導入可直接使用)
- 然后在 load 方法里面用 Method Swzilling 方法替換交換 ViewDidAppear 方法,代碼如下:
- #pragma mark --------- UINavigationBarDelegate
- - (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPushItem:(UINavigationItem *)item {
- //設置導航欄返回按鈕文字為透明的,可能造成導航標題不居中的問題
- [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateNormal];
- [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateHighlighted];
- return YES;
- }
責任編輯:武曉燕
來源:
網羅開發