禁用数组中的导航按钮

时间:2013-11-03 22:17:25

标签: button ios7 uinavigationbar

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

我有一个简单的请求:如何禁用此阵列中的按钮?例如,在特定情况下,我希望禁用“共享”按钮,我将如何进行此操作?提前谢谢!

2 个答案:

答案 0 :(得分: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 = NO;

if(...){

self.shareBarButton.enabled = YES;

}

答案 1 :(得分: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;
    }
  }
}