2011-09-22 68 views
3

我通過IB添加了一個NavigationBar,我嘗試以編程方式添加BarButtonItem .....但它不起作用。添加BarButtonItem到NavigationBar

- (void)viewDidLoad { 

    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:@"Edit"style:UIBarButtonItemStyleBordered target:self action:@selector(EditTable:)]; 
    [self.navigationItem setLeftBarButtonItem:self.addButton]; 
    [super viewDidLoad]; 
} 
+0

您是否看到沒有任何按鈕的導航欄? – user523234

+0

你有沒有得到這個固定的Chandu? – chown

+0

是@chown我修好了。但以不同的方式 – Chandu

回答

4

嘗試這樣做:

self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:@selector(backButtonTapped:)]; 
+0

沒有它沒有工作 – Chandu

1

你的情況,試試這個:

UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:@"Edit"style:UIBarButtonItemStyleBordered target:self action:@selector(EditTable:)]; 
[self.navigationItem setLeftBarButtonItem:addButton]; 

我想這可能會奏效。

+0

我試過但沒有運氣.... – Chandu

+0

我認爲它適用於以編程方式添加的導航欄...但我從IB添加它 – Chandu

+1

如果您已經從IB添加了BarButtonItem那麼你根本不需要寫這個代碼。只需爲酒吧按鈕項目定義一個Outlet,將其放在導航欄上,並像在UIButton中一樣連接它的方法。 –

0
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] init]; 
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Edit"style:UIBarButtonItemStyleBordered target:self action:@selector(EditTable:)]; 
self.navigationItem.leftBarButtonItem = addButton; 
self.navigationItem.leftBarButtonItem.enabled = YES; 
+0

不,先生,沒有得到它然而......我在模態視圖中添加了這個欄(如果它與正常的一個有所不同)。 ) – Chandu

0

對於一些視圖leftBarButtonItem不起作用,你需要使用backBarButtonItem。試試這個:

- (void)viewDidLoad { 
    [self.navigationItem setBackBarButtonItem:[[[UIBarButtonItem alloc] initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(EditTable:)] autorelease]; 
    // Or, if that doesnt work for some reason use: 
    // [self.navigationItem setLeftBarButtonItem:[[[UIBarButtonItem alloc] initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(EditTable:)] autorelease]; 
    [super viewDidLoad]; 
} 

此外,您創建的viewDidLoad稱爲addButton範圍內的變量,但你正在嘗試設置屬性self.addButtonleftBarButtonItem

無論是從self.addButton刪除self.在:

[self.navigationItem setLeftBarButtonItem:self.addButton]; 

或初始化屬性,而不是使用相同的名稱創建一個新的項目:

1

你在做什麼是對的,但到目前爲止,您只是將addButton作爲leftBarButtonItem添加到UINavigationItem中。要將其添加到導航欄,您需要將導航項推到它上面,類似於如何將新的UIViewController添加到UINavigationController。假設你命名你的UINavigationBar navBar:

UINavigationItem *navigationItem = [[UINavigationItem alloc] init]; 

self.addButton = [[UIBarButtonItem alloc] initWithTitle:@"Edit"style:UIBarButtonItemStyleBordered target:self action:@selector(EditTable:)]; 
[navigationItem setLeftBarButtonItem:self.addButton]; 

[self.navBar pushNavigationItem:navigationItem animated:NO]; 
[navigationItem release]; 

希望幫助!

+0

如果你使用的是UINavigationController,所有其他的方法都可以工作,因爲它將在內部處理它的UINavigationBar的navigationItem推送/彈出。如果你使用沒有控制器的UINavigationBar,你必須自己做。 – Ashwin

相關問題