如何在 objective c 中禁用以编程方式创建的 UIBarButtonItem?

How to disable programmatically created UIBarButtonItem in objective c?

我以编程方式创建了一个工具栏,并以编程方式在工具栏中添加了四个 UIBarButtonItem。
文本视图开始编辑时会出现此按钮,如果文本视图中没有文本,清除按钮和翻译按钮将禁用。
这是我的四个按钮创建代码。

UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
numberToolbar.backgroundColor = [UIColor lightGrayColor];

numberToolbar.items = [NSArray arrayWithObjects:
                       [[UIBarButtonItem alloc]initWithTitle:@"Hide" style:UIBarButtonItemStyleDone target:self action:@selector(cancelKeyboard)],
                       [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                       [[UIBarButtonItem alloc]initWithTitle:@"Clear" style:UIBarButtonItemStyleDone target:self action:@selector(clearTextView)],
                       [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                       [[UIBarButtonItem alloc]initWithTitle:@"Paste" style:UIBarButtonItemStyleDone target:self action:@selector(paste)],
                       [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                       [[UIBarButtonItem alloc]initWithTitle:@"Translate" style:UIBarButtonItemStyleDone target:self action:@selector(translate)],
                       nil];
[numberToolbar sizeToFit];
_sorceTextview.inputAccessoryView = numberToolbar;
_sorceTextview.autocorrectionType = UITextAutocorrectionTypeNo;

现在如何禁用清除和翻译按钮:

-(BOOL)textViewShouldBeginEditing:(UITextView *)textView {} 

方法?请帮助。

为这些按钮使用实例变量。然后你可以根据需要设置enabled 属性。

@implementation MyViewController {
    UIBarButtonItem *_btnClear;
    UIBarButtonItem *_btnTranslate;
}

然后在你的工具栏设置代码中:

_btnClear = [[UIBarButtonItem alloc]initWithTitle:@"Clear" style:UIBarButtonItemStyleDone target:self action:@selector(clearTextView)];
_btnTranslate = [[UIBarButtonItem alloc]initWithTitle:@"Translate" style:UIBarButtonItemStyleDone target:self action:@selector(translate)];
UIBarButtonItem *flex = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

numberToolbar.items = @[
                       [[UIBarButtonItem alloc]initWithTitle:@"Hide" style:UIBarButtonItemStyleDone target:self action:@selector(cancelKeyboard)],
                       flex,
                       _btnClear,
                       flex,
                       [[UIBarButtonItem alloc]initWithTitle:@"Paste" style:UIBarButtonItemStyleDone target:self action:@selector(paste)],
                       flex,
                       _btnTranslate
                       ];

然后在任何需要禁用的地方你可以这样做:

_btnClear.enabled = NO;

并启用:

_btnClear.enabled = YES;