Question

I am trying to dismiss a UIPickerView using a toolbar similar to the inputAccessoryView on keyboards.

I am using the same UIToolbar for both my text field and my picker, the textfield will dismiss properly, but the picker doesn't even recognize my touch on the button.

This is the code I am using to create the toolbar:

UIToolbar *tipToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
tipToolbar.barStyle = UIBarStyleDefault;
UIBarButtonItem *donebtn = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(resignResponder:)];
tipToolbar.items = [NSArray arrayWithObjects:
                    [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                    donebtn, nil
];
[tipToolbar sizeToFit];
_outlet_txt_ipaddr.inputAccessoryView = tipToolbar;
[_outlet_picker addSubview:tipToolbar];

And this is the action that will dismiss the keyboard or the picker:

- (IBAction)resignResponder:(id)sender{
    [_outlet_txt_ipaddr resignFirstResponder];
    [_outlet_picker resignFirstResponder];
}

The toolbar appears on the picker view, but my tap on the done button isn't even showing the animation let alone call the resignResonder action.

Was it helpful?

Solution

for picker view [_outlet_picker resignFirstResponder]; will not work.

you need to implement the delegate for picker view.

try this code

UIToolbar *tipToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
tipToolbar.barStyle = UIBarStyleDefault;
UIBarButtonItem *donebtn = [[UIBarButtonItem alloc] initWithTitle:@"Done"   style:UIBarButtonItemStyleDone target:self action:@selector(resignResponder:)];
tipToolbar.items = [NSArray arrayWithObjects:
                [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                donebtn, nil
 ];
[tipToolbar sizeToFit];
_outlet_txt_ipaddr.inputAccessoryView = tipToolbar;

_outlet_picker.delegate=self;
_outlet_picker.dataSource=self;
_outlet_picker.showsSelectionIndicator=YES;

[self.view addSubview:outlet_picker];

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
 {
return 1;
 }

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
return [pickerValueAry count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
NSMutableArray *ary = [[NSMutableArray alloc] initWithArray:pickerValueAry];
id str=[ary objectAtIndex:row];
return str;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{    
NSLog(@"selectedRowInPicker >> %d",row);
}  

you can dismiss the picker view on row select.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top