您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 常見問題:動態修改 UINavigationController 的 rightBarButtonItem 標題

編輯:iOS 開發綜合

想動態修改 navigationItem 右側按鈕的標題,卻發現怎麼改都不生效?這是許多初學者都會遇到的經典問題。本文還原整個排查過程,並給出正解。

一、初始化

在 viewDidLoad 中,為 navigationItem 添加一個名為「添加分欄」的按鈕:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.rightBarButtonItem.title = @"添加分欄";
    [self.navigationItem.rightBarButtonItem initWithBarButtonSystemItem:UIBarButtonSystemItemUndo target:self action:@selector(myAction)];
}

二、嘗試更改按鈕名稱失敗

於是嘗試透過如下方式修改按鈕名稱,卻發現完全無效:

-(void)onSelectionChanged:(id)selection {
    self.navigationItem.rightBarButtonItem.title = @"編輯";
}

三、原因分析

為何直接設置 title 無效呢?查閱蘋果官方文件,UIBarButtonItem 的父類 UIBarItem 的 title 屬性描述寫道:

You should set this property before adding the item to a bar. The default value is nil.

也就是說,title 應該在把該項目加入 bar 之前設定,一旦加入後就無法再修改,只能重置整個控件本身。

四、正確做法

思路一(無效)

單純改標題不行,那再呼叫一次初始化方法呢?程式碼如下,但最終還是不行:

self.navigationItem.rightBarButtonItem.title = @"編輯";
[self.navigationItem.rightBarButtonItem initWithBarButtonSystemItem:UIBarButtonSystemItemUndo target:self action:@selector(myAction)];

思路二(正確)

既然只改標題不起作用,那就把整個按鈕換掉吧!建立一個新的 UIBarButtonItem,用它替換掉原本的 rightBarButtonItem,這次終於成功了:

UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemUndo target:self action:@selector(changeWellColumnAction)];
temporaryBarButtonItem.title = @"編輯";
self.navigationItem.rightBarButtonItem = temporaryBarButtonItem;
[temporaryBarButtonItem release];

關鍵在於:UIBarItem 的 title 必須在加入 bar 之前設定,因此要動態更改標題,正確思路是「重新建立一個按鈕並替換」,而非修改既有按鈕的屬性。

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