目标 c - 将 UIBarButtonItem 添加到 UIToolbar



我需要将按钮添加到UINavigationController的ui工具栏,这也是我的根。我希望当一个特定的UIViewController被显示时,工具栏会出现。因此,我把这段代码放在我的UIViewController子类的viewDidLoad方法中:

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对我来说是没有用的,它只是一个测试。我还试图分配一个新的数组,而不是从组件复制一个。忽略缺失的版本,这只是测试代码。

我读了很多关于这个的问题,但没有答案似乎有助于使它工作。你知道在这段代码中什么可能是不正确的吗?

似乎您正在尝试使nil的可变副本在行

[self.navigationController.toolbar.items mutableCopy];

默认方法navigationController.toolbar。items不包含任何项并返回nil

方法- (void)setToolbarItems:(NSArray*)toolbarItems animated:(BOOL)animated如果你把它发送给UINavigationController,它什么也不做。您需要将工具栏项设置为由导航控制器管理的控制器。这一行将使您的按钮可见:

[self setToolbarItems:theItems animated:NO];

最新更新