UIBarbuttonItem 对 UIToolBar 的操作未被调用

The action of UIBarbuttonItem on UIToolBar not called

我遇到了麻烦,因为没有调用 UIToolBar 上的 UIBarbuttonItem 的操作。
在下面的代码中,虽然 toolBar 上的 doneBtn 被点击了,但是动作 doneBtnAction: 没有被调用。
你有什么办法解决它吗?

- (void)viewDidLoad {
    UIPickerView *pickerView = [[UIPickerView alloc] init];

    UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, -44, 320, 44)];
    UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(doneBtnAction:)];
    UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    toolBar.items = @[flex, doneBtn];
    [pickerView addSubview:toolBar];

    UITextField *textField = [[UITextField alloc] init];
    textField.inputView = pickerView;
}

- (void)doneBtnAction:(UIBarButtonItem *)sender {
    NSLog(@"%@", sender);
}

不要将工具栏添加为选取器视图的子视图,尤其是负 y 原点(没有触摸到达工具栏,因为点击被剪切到选取器视图的框架)。

相反,将工具栏设为文本字段的 inputAccessoryView

textField.inputAccessoryView = toolBar;

完整代码:

- (void)viewDidLoad {
    UIPickerView *pickerView = [[UIPickerView alloc] init];

    UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(doneBtnAction:)];
    UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    toolBar.items = @[flex, doneBtn];

    UITextField *textField = [[UITextField alloc] init];
    textField.inputView = pickerView;
    textField.inputAccessoryView = toolBar;
}

另一个注意事项 - 为什么不对栏按钮项目使用标准系统完成类型?