2012-04-11 123 views
6

我是iOS開發新手。我在我的iPad應用程序視圖中創建了一個導航欄。我不需要導航控制器,這就是爲什麼我只添加了導航欄。現在我想在該導航欄中添加按鈕。我嘗試了很多,但沒有成功。是否可以添加只有導航欄的按鈕?如果是的話,建議我一些示例代碼。如何在沒有導航控制器的情況下在導航欄中添加欄按鈕。

「我沒有導航控制器或需要它,我只想在一個視圖中添加導航欄。」

貝婁是我的代碼,我寫的viewDidLoad中()提前

UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 1026, 50)]; 
[navBar setTintColor:[UIColor blackColor]]; 
[navBar setDelegate:self]; 
[self.view addSubview:navBar]; 

由於添加導航欄....

回答

1

您可以添加按鈕,導航欄,如下所示:

UIBarButtonItem *btnSave = [[UIBarButtonItem alloc] 
           initWithTitle:@"Save" 
           style:UIBarButtonItemStyleBordered 
           target:self 
          action:@selector(save_Clicked:)]; 
navBar.rightBarButtonItem = btnSave; 
[btnSave release]; 

UIBarButtonItem *btnCancel = [[UIBarButtonItem alloc] 
           initWithTitle:@"Cancel"          
           style:UIBarButtonItemStyleBordered 
           target:self 
           action:@selector(cancel_Clicked:)]; 
navBar.leftBarButtonItem = btnCancel; 
[btnCancel release]; 
+2

在上面的代碼這一行給我錯誤。 'navBar.rightBarButtonItem = btnSave;' 錯誤:語義問題:在'UINavigationBar *'類型的對象上找不到屬性'rightBarButtonItem'' – 2012-04-11 06:31:20

+0

您也可以將導航欄添加到xib文件,然後您可以將bar按鈕項添加到它。 – 2012-04-11 07:31:47

5
UIBarButtonItem *bi1 = [[UIBarButtonItem alloc] initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(editButton)]; 

bi1.style = UIBarButtonItemStyleBordered; 
bi1.tintColor = [UIColor colorWithWhite:0.305f alpha:0.0f]; 

self.navigationItem.rightBarButtonItem = bi1; 

[bi1 release]; 
11

我使用Interface Builder在UITableViewController中創建靜態tableView。 這個UITableViewController以模態顯示。然後,我添加了一個沒有UINavigationController的NavigationBar,如下所示:

//Creating the plain Navigation Bar 
UINavigationBar *headerView = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; 

//The UINavigationItem is neede as a "box" that holds the Buttons or other elements 
UINavigationItem *buttonCarrier = [[UINavigationItem alloc]initWithTitle:@"Sign-In"]; 

//Creating some buttons: 
UIBarButtonItem *barBackButton = [[UIBarButtonItem alloc] initWithTitle:@"Zurück" style:UIBarButtonItemStyleDone target:self action:@selector(signInBackPressed:)]; 
UIBarButtonItem *barDoneButton = [[UIBarButtonItem alloc] initWithTitle:@"Fertig" style:UIBarButtonItemStylePlain target:self action:@selector(signInDonePressed:)]; 

//Putting the Buttons on the Carrier 
[buttonCarrier setLeftBarButtonItem:barBackButton]; 
[buttonCarrier setRightBarButtonItem:barDoneButton]; 

//The NavigationBar accepts those "Carrier" (UINavigationItem) inside an Array 
NSArray *barItemArray = [[NSArray alloc]initWithObjects:buttonCarrier,nil]; 

// Attaching the Array to the NavigationBar 
[headerView setItems:barItemArray]; 

// Adding the NavigationBar to the TableView 
[self.tableView setTableHeaderView:headerView]; 

我希望這有助於某人!