UIToolBar 上的 UIBarbuttonItem 动作没有被调用

3

我遇到了困难,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);
}

你看到 doneBtn 在点击时有动画效果吗?toolBarpickerView 中的定位是如何实现的? - hatfinch
调试查看 UIPickerViewUIToolbarUITextField 的框架层级结构。希望能对您有所帮助。 - SeraZheng
1个回答

4
不要将工具栏作为选择器视图的子视图添加,特别是使用负 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;
}

另外一点需要注意 - 为什么不在工具栏按钮上使用标准的系统 Done 类型?


这个问题得以解决,多亏了你的支持。谢谢。 - kusumoto_teruya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接