想動態修改 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 之前設定,因此要動態更改標題,正確思路是「重新建立一個按鈕並替換」,而非修改既有按鈕的屬性。