In my UIViewController I want to add a UIBarButtonItem in the Toolbar, but the new Button doesn't appear. What am I doing wrong?
- (void)doLogin:(NSString *)name password:(NSString *)password {
// 1.: start the Thread:
NSInvocationOperation *invOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(backgroundTaskLogin:) object:request];
[self.opQueue addOperation:invOperation];
}
- (void)backgroundTaskLogin:(NSString *)request2 {
// 2.: jump back in the Main Thread in show a cancel button in den toolbar:
[self performSelectorOnMainThread:@selector(showCancelButton) withObject:nil waitUntilDone:NO];
}
- (void)showCancelButton {
// 3.: add a new Cancel-Button in the Toolbar:
UIBarButtonItem *tempButtonCancel = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelLogin)];
NSMutableArray *myButtons = (NSMutableArray *)self.toolbarItems;
NSLog(@"Count buttons: %d", [self.toolbarItems count]); // DEBUGGER: 2
[myButtons addObject:tempButtonCancel];
[tempButtonCancel release];
NSLog(@"Count buttons: %d", [self.toolbarItems count]); // DEBUGGER: 3
// PROBLEM: I don't see the new Toolbar-Button :开发者_如何学Go-(
}
You can't rely on self.toolbarItems
being a mutable array. It may be one in your case if you assigned a mutable array to that property before but you can't expect the view controller to notice a change in a property if you don't use the documented interface.
Create a new array and use the setter to assign it to toolbarItems
:
NSMutableArray *newToolbarItems = [NSMutableArray arrayWithArray:self.toolbarItems];
[newToolbarItems addObject:tempButtonCancel];
self.toolbarItems = newToolbarItems;
The code in Ole's post will fix your bug, but not for the reason he suggests (since it appears that you are successfully adding an item to the array, even if that shouldn't be mutable most of the time). You have to call setToolbarItems:
after duplicating and modifying the items array because the UIToolbar does not detect that changes have been made to it's array otherwise.
You can also use setToolbarItems:animated:
to fade things in nicely ;-)
精彩评论