Search code examples
ios7uipickerview

UIPickerView toolbar buttons not working


I'm trying to add a toolbar to a UIPicker. I've seen that the right way to go is this way:

UIToolbar* toolbarWeight= [[UIToolbar alloc] initWithFrame:CGRectMake(0,0,320,44)];
UIBarButtonItem *barButtonDone1 = [[UIBarButtonItem alloc] initWithTitle:@"Done"
                                                                               style:UIBarButtonItemStyleBordered target:self action:@selector(gotoNextField:)];
[toolbarWeight setItems:[NSArray arrayWithObject:barButtonNext1] animated:YES]; 

weightPickerView = [[UIPickerView alloc]init];
[weightPickerView addSubview:toolbarWeight];

While:

-(IBAction)gotoNextField:(id)sender{
    NSLog(@"Works");
}

The picker works just fine but the button doesn't work. After doing some research, I've tried this approach: (I suspected that the problem was related to the UIBarButtonItem action)

UIButton* myBtn = [[UIButton alloc]init];
myBtn.frame = CGRectMake(0,0,50,24);
[myBtn addTarget:self action:@selector(gotoNextField:) forControlEvents:UIControlEventTouchUpInside];
[myBtn setTitle:@"Next!" forState:UIControlStateNormal];
[myBtn setBackgroundColor:[UIColor orangeColor]];
UIBarButtonItem *barButtonNext1 = [[UIBarButtonItem alloc] initWithCustomView:myBtn];
[toolbarWeight setItems:[NSArray arrayWithObject:barButtonNext1] animated:YES];

Doesn't work either. The button appears but doesn't get selected/respond to touchUpInside.


Solution

  • As adding a toolbar to the pickerView, the toolbar is added behind the picker preventing the buttons from responding to touch events.

    Encapsulating both the picker and the toolbar in a view, and making it an inputView (to make both the picker and the toolbar popup together) provides the desired solution.

    weightPickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 44, 320, 216)];
    weightPickerView.tag = 13;
    UIView* genericWeightView = [[UIView alloc]initWithFrame:CGRectMake(0, 219, 320, 266)];
    [genericWeightView addSubview:toolbarWeight];
    [genericWeightView  addSubview:weightPickerView];
    

    and then:

    [weight_txtField setInputView:genericWeightView];