我需要將按鈕添加到UINavigationController的UIToolbar,UINavigationController也是我的根。我想在顯示特定UIViewController時顯示UIToolbar。因此,我把這個代碼在我的UIViewController子類的我viewDidLoad方法:將UIBarButtonItem添加到UIToolbar
UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithTitle:@"Title" style:UIBarButtonItemStyleBordered target:self action:@selector(doSomething)];
item.width = 300;
item.tintColor = [UIColor whiteColor];
UIBarButtonItem* item2 = [[UIBarButtonItem alloc] initWithTitle:@"Title2" style:UIBarButtonItemStyleBordered target:self action:@selector(doSomething)];
NSMutableArray* theItems = [self.navigationController.toolbar.items mutableCopy];
[theItems addObject:item];
[theItems addObject:item2];
[self.navigationController.toolbar setBarStyle:UIBarStyleBlackOpaque];
[self.navigationController setToolbarHidden:NO animated:YES];
[self.navigationController setToolbarItems:theItems animated:NO];
//self.navigationController.toolbarItems = theItems; // Tried both
UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
label.text = @"kjhdkjhadsda";
[self.navigationController.toolbar addSubview:label];
這隻能說明在正確的位置上的UILabel,似乎沒有別的。 UILabel對我來說沒用,它只是一個測試。我也嘗試分配一個新的數組,而不是從組件中複製一個。忽略丟失的版本,這只是測試代碼。
我看了很多關於這個問題的問題,但沒有答案似乎有助於使它工作。任何想法可能不會在這段代碼中確定嗎?
我指定我也嘗試分配一個新的。也許不清楚我是指那一個,對不起。 – 2013-03-06 12:35:01
你有沒有檢查你的self.navigationController!= nil。你的代碼看起來不錯,應該工作。並嘗試通過UIViewController的方法設置工具欄項[self setToolbarItems:theItems animated:NO]; – 2013-03-06 12:41:30
Il self.navigationController是零我不希望工具欄顯示和標籤要正確添加,對不對?我剛剛嘗試了UIViewController中的方法setToolbarItems,不知道它是否存在,但沒有出現按鈕。任何其他想法?也許代碼是好的,但可能有其他的東西阻止按鈕顯示? – 2013-03-06 12:56:58