Search code examples
iphoneuipickerview

How to add a button on top of a PickerView and How to dismiss the PickerView on click of that button?


I have a UIPickerView. I want a done button on top of the pickerview and i want to dismiss the picker view on click of the done button. Can u please help me on this?


Solution

  • add action sheet to your view and then add tool bar with done button at top of action sheet and below add your your picker to action sheet in done button click write below method to dismiss action sheet

    [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
    
    actionSheet=[[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
        [actionSheet showInView:self.view];
    UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0,320,40)];
    [pickerToolbar sizeToFit];
        pickerToolbar.barStyle = UIBarStyleBlackTranslucent;
    NSMutableArray *barItems = [[NSMutableArray alloc] init];
    
        UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonSystemItemCancel target:self action:@selector(cancel_clicked:)];
        [barItems addObject:cancelBtn];
        [cancelBtn release];
        UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        [barItems addObject:flexSpace];
        [flexSpace release];
        UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(done_clicked:)];
        [barItems addObject:doneBtn];
        [doneBtn release];
        [pickerToolbar setItems:barItems animated:YES];
        [actionSheet addSubview:pickerToolbar];
        [barItems release];
        [pickerToolbar release];
    
    UIPickerView *picker = [[UIPickerView alloc] init];
    picker.frame = CGRectMake(0, 44, 320, 216);
    picker.delegate  = self;
            picker.dataSource = self;
            picker.showsSelectionIndicator = YES;
    [actionSheet addSubview:picker];
    [picker release];
    
    -(void)done_clicked:(id)sender
    {
        [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
    }
    -(void)cancel_clicked:(id)sender
    {
        [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
    }