2012-08-09 225 views
1

在我viewDidLoad方法中,我有以下:添加按鈕自定義導航欄

navigBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; 
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonSystemItemAction target:self action:@selector(btnClicked:)]; 
[self.view addSubview:navigBar]; 

的按鈕不會顯示在所有!我錯過了什麼?

回答

4
// create the navigation bar and add it to the view 
UINavigationBar *navigationBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; 
[self.view addSubview:navigationBar]; 

// create a button 
UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonSystemItemAction target:self action:@selector(btnClicked:)]; 

// create a UINavigationItem and add the button in the right hand side 
UINavigationItem *navItem = [[UINavigationItem alloc] initWithTitle:nil]; 
navItem.rightBarButtonItem = button; 

// add the UINavigationItem to the navigation bar 
[navigationBar pushNavigationItem:navItem animated:NO]; 
3

在導航欄上設置按鈕,然後在導航上創建一個BarButtonItem

barbutton=[UIBarButtonItem alloc] ]initWithTitle...... 
navigation.navigationController.rightBarButton= barbutton; 
+3

我真的不明白你在說什麼。 – Jordan 2012-08-09 18:44:38

3

首先閱讀:

當您使用導航欄作爲一個獨立的對象,你是負責提供內容。與其他類型的視圖不同,您不直接將子視圖添加到導航欄。相反,您使用導航項目(UINavigationItem類的一個實例)來指定要顯示的按鈕或自定義視圖。導航項目具有用於指定導航欄左側,右側和中心視圖以及用於指定自定義提示字符串的屬性。

導航欄管理一堆UINavigationItem對象。雖然堆棧主要用於支持導航控制器,但您也可以使用它來實現自己的自定義導航界面。堆棧中最頂端的項目表示其內容當前由導航欄顯示的導航項目。使用pushNavigationItem:animated:方法將新的導航項目推送到堆棧上,並使用popNavigationItemAnimated:方法從堆棧中彈出項目。這兩個變化都可以爲用戶帶來好處。

所以基本上你需要做的是:

[navigBar pushNavigationItem:self.navigationItem animated:NO];