iOS常見問題之動態修改UINavigationController的rightBarButtonItem的title
1.初始化
在viewDidLoad裡,為navigationItem添加名稱為“添加分欄”的按鈕
- (void)viewDidLoad{ [super viewDidLoad];// Do any additional setup after loading the view. self.navigationItem.rightBarButtonItem.title = @添加分欄; [self.navigationItem.rightBarButtonItem initWithBarButtonSystemItem:UIBarButtonSystemItemUndo target:self action:@selector(myAction)]; }
2.試圖更改按鈕名稱失敗嘗試通過如下方式修改按鈕的名稱,但是失敗了
-(void)onSelectionChanged:(id)selection{ self.navigationItem.rightBarButtonItem.title = @編輯; }
3.原因分析
為何直接設定backBarButtonItem的title無效呢?
查看蘋果文檔UIBarButtonItem的父類UIBarItem的title屬性描述:
You should set this property before adding the item to a bar. The default value is nil.故無法修改其title,只能重設這個控制項本身。
4.正確代碼4.1思路一單單修改標題不行,是不是還應該再調用一下初始化方法呢?代碼如下,最終還是不行啊,無語了
self.navigationItem.rightBarButtonItem.title = @編輯;[self.navigationItem.rightBarButtonItem initWithBarButtonSystemItem:UIBarButtonSystemItemUndotarget:selfaction:@selector(myAction)];
4.1思路二既然只改標題不起作用,那就把整個按鈕換掉吧! 建立一個新的按鈕,用這個新按鈕替換self.navigationItem.rightBarButtonItem,這次總算可以了,謝天謝地!!!
UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemUndo target:self action:@selector(changeWellColumnAction)]; temporaryBarButtonItem.title = @編輯; self.navigationItem.rightBarButtonItem = temporaryBarButtonItem; [temporaryBarButtonItem release];