iOS常見問題之動態修改UINavigationController的rightBarButtonItem的title – iPhone手機開發技術文章 iPhone軟體開發教學課程

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:UIBarButtonSystemItemUndo
								target:self
								action:@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];

 

發佈留言