2016-09-18 58 views
0

我嘗試以編程方式添加UINavigationBar並設置欄按鈕項目。 我想:沒有出現右欄按鈕

self.artificialNavBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)]; 
    self.artificialNavBar.backgroundColor = [UIColor whiteColor]; 
    UIBarButtonItem *bbiDone = [[UIBarButtonItem alloc] initWithTitle:@"Готово" style:UIBarButtonItemStyleDone target:nil action:nil]; 
    UIBarButtonItem *bbiTry = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleDone target:nil action:nil]; 
UINavigationItem *navItem = [[UINavigationItem alloc] init]; 

    navItem.leftBarButtonItem = bbiDone; 
    navItem.rightBarButtonItem = bbiTry; 

    self.artificialNavBar.items = @[ navItem ]; 
    [self.view addSubview:self.artificialNavBar]; 

然而,似乎只剩欄按鈕,右側是隱藏的。我錯過了什麼?

+0

顯示'artificialNavBar'聲明。 –

+0

@ Mr.UB屬性(非原子)UINavigationBar * artificialNavBar; –

+0

也使這強勁。 –

回答

1

在你寫這些,然後用下面的代碼替換代碼這個類的.h文件中聲明

@property (nonatomic, strong) UINavigationItem *navItem; 

self.artificialNavBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)]; 
self.artificialNavBar.backgroundColor = [UIColor whiteColor]; 
[self.view addSubview:self.artificialNavBar]; 

UIBarButtonItem *bbiDone = [[UIBarButtonItem alloc] initWithTitle:@"Готово" style:UIBarButtonItemStyleDone target:nil action:nil]; 
UIBarButtonItem *bbiTry = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleDone target:nil action:nil]; 

self.navItem = [[UINavigationItem alloc] init]; 
[self.navItem setLeftBarButtonItem:bbiDone animated:NO] 
[self.navItem setRightBarButtonItem:bbiTry animated:NO] 

[self.artificialNavBar setItems:@[self.navItem] animated:NO] 

並確保navbar是非原子和強大的。

+0

即時通訊不使用故事板.. –

+0

沒問題。你可以使用這段代碼。只是刪除iboutlet ..這是一個錯誤。我已經更新了答案 –

+0

好吧,我嘗試,順便說一句,屬性是默認強,如果你不指定其他。 –