1

在我的 UIViewController 中,我想在工具栏中添加一个 UIBarButtonItem,但没有出现新的 Button。我究竟做错了什么?

- (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 :-(
}
4

2 回答 2

2

你不能依赖于self.toolbarItems成为一个可变数组。如果您之前为该属性分配了一个可变数组,则可能是您的情况,但如果您不使用记录的接口,您不能期望视图控制器注意到属性的更改。

创建一个新数组并使用 setter 将其分配给toolbarItems

NSMutableArray *newToolbarItems = [NSMutableArray arrayWithArray:self.toolbarItems];
[newToolbarItems addObject:tempButtonCancel];
self.toolbarItems = newToolbarItems;
于 2010-11-16T15:30:47.820 回答
0

Ole 帖子中的代码将修复您的错误,但不是出于他建议的原因(因为您似乎成功将项目添加到数组中,即使大部分时间不应该是可变的)。您必须setToolbarItems:在复制和修改 items 数组后调用,因为 UIToolbar 不会检测到已对其数组进行了更改。

你也可以setToolbarItems:animated:用来很好地淡入淡出;-)

于 2010-11-16T15:38:26.947 回答