2013-03-06 114 views
0

我需要将按钮添加到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对我来说没用,它只是一个测试。我也尝试分配一个新的数组,而不是从组件中复制一个。忽略丢失的版本,这只是测试代码。

我看了很多关于这个问题的问题,但没有答案似乎有助于使它工作。任何想法可能不会在这段代码中确定吗?

回答

2

似乎您试图使可变副本线

[self.navigationController.toolbar.items mutableCopy]; 

默认方法navigationController.toolbar.items NAS没有任何项目,并返回

更新

方法- (void)setToolbarItems :(NSArray *)toolbarItems animated:(BOOL)animated如果将它发送给UINavigationController,则不会执行任何操作。您需要将工具栏项目设置为由导航控制器管理的该控制器。此行将使您的按钮可见:

[self setToolbarItems:theItems animated:NO]; 
+0

我指定我也尝试分配一个新的。也许不清楚我是指那一个,对不起。 – 2013-03-06 12:35:01

+0

你有没有检查你的self.navigationController!= nil。你的代码看起来不错,应该工作。并尝试通过UIViewController的方法设置工具栏项[self setToolbarItems:theItems animated:NO]; – 2013-03-06 12:41:30

+0

Il self.navigationController是零我不希望工具栏显示和标签要正确添加,对不对?我刚刚尝试了UIViewController中的方法setToolbarItems,不知道它是否存在,但没有出现按钮。任何其他想法?也许代码是好的,但可能有其他的东西阻止按钮显示? – 2013-03-06 12:56:58

相关问题