0

我的 UINavigationController 右侧有两个按预期工作的按钮。这是我用来实现这一点的代码:

// Share Button
UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
[shareButton setFrame:CGRectMake(0,0,19,21)];
[shareButton addTarget:self action:@selector(shareButton) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *shareBarButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(shareButton)] autorelease];
shareBarButton.tintColor = [UIColor whiteColor];

// Snapback Button
UIButton *navSnapbackButton = [UIButton buttonWithType:UIButtonTypeCustom];
[navSnapbackButton setFrame:CGRectMake(0,0,26,21)];
[navSnapbackButton setImage:[UIImage imageNamed:@"Snapback.png"] forState:UIControlStateNormal];
[navSnapbackButton addTarget:self action:@selector(snapbackButton) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *navSnapbackBarButton = [[[UIBarButtonItem alloc] initWithCustomView:navSnapbackButton] autorelease];
navSnapbackButton.tintColor = [UIColor whiteColor];

// Right Toolbar Button Setup
[self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:navSnapbackBarButton, shareBarButton, nil]];

我有一个简单的要求:如何禁用此数组中的按钮?例如说在特定条件下我希望禁用共享按钮,我将如何执行此操作?提前致谢!

4

2 回答 2

0

代替 UIBarButtonItem *shareBarButton 的局部变量,将其声明为 @interface 部分中的属性,以便您可以在其他方法中访问它:

@property(强,非原子) UIBarButtonItem *shareBarButton;

...

然后像您所做的那样在您的工具栏设置例程中分配它:

// 分享按钮

shareBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(shareButton:)];

shareBarButton.tintColor = [UIColor whiteColor];

...

按钮的操作如下所示:

-(void)shareButton:(id)sender {

}

...

然后在 shareButton 操作或其他方法中,您现在可以设置 enabled 属性:

self.shareBarButton.enabled = 否;

如果 (...) {

self.shareBarButton.enabled = 是;

}

于 2013-11-08T06:11:47.617 回答
0

Ann Taylor 的回答非常好,我会这样做,但是如果您不想在视图中将这个 UIBarButton 作为界面属性,您可以这样做:

UIBarButtonItem *btn1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(performAction:)];
btn1.tag = 0;
UIBarButtonItem *btn2 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"_ui_image"] style:UIBarButtonItemStylePlain target:self action:@selector(performAction:)];
btn2.tag = 1;
self.navigationItem.rightBarButtonItems = @[btn1,btn2];

在禁用方法中:

- (void)performAction:(id)sender
{
  NSArray *_barButtons = self.navigationItem.rightBarButtonItems;
  UIBarButtonItem *_barButton;
  for (_barButton in _barButtons) {
    if (_barButton.tag == 0) {
        _barButton.enabled = NO;
    }
  }
}  

我。

于 2013-11-08T11:57:55.907 回答