Domanda

I need to add buttons to the UIToolbar of a UINavigationController, which is also my root. I want the UIToolbar to appear when a specific UIViewController is shown. Therefore, I placed this code in my viewDidLoad method of my UIViewController subclass:

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];

This only shows the UILabel in the correct position, nothing else appears. The UILabel is useless for me, it is just a test. I also tried to allocate a new array instead of copying the one from the component. Ignore the missing releases, this is only test code.

I read many questions about this but no answer seem to help making it work. Any idea what might not be ok in this code?

È stato utile?

Soluzione

Seems that you are trying make mutable copy of nil in line

[self.navigationController.toolbar.items mutableCopy];

By default method navigationController.toolbar.items nas no items and returns nil

Update

Method - (void)setToolbarItems:(NSArray*)toolbarItems animated:(BOOL)animated does nothing if you send it to UINavigationController. You need to set toolbar items to that controller who is managed by a navigation controller. This line will make your buttons visible:

[self setToolbarItems:theItems animated:NO];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top