我以编程方式创建一个工具栏,并以编程方式在工具栏中添加四个UIBarButtonItem。当文本视图开始编辑时,如果在textview中没有文本,则清除按钮和转换按钮将被禁用。这是我的四个按钮创建代码。

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;

10-05 20:24
查看更多