Search code examples
iosuibuttonuipickerviewuiactionsheet

How to get pickervalue from action sheet in iOS?


In my app, when button is pressed, I am launching UIActionSheet with UIPickerView and UIToolBar in it. Its working perfectly by using the following code. I am trying to get the picker value and set that value to the called button, but I couldn't find the exact solution for it.

- (IBAction)showPicker:(id)sender {

 actionSheet = [[UIActionSheet alloc] initWithTitle:nil 
                                                         delegate:self
                                                cancelButtonTitle:nil
                                           destructiveButtonTitle:nil
                                                otherButtonTitles:nil];//as we want to display a subview we won't be using the default buttons but rather we're need to create a toolbar to display the buttons on 

[actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];

CGRect pickerFrame = CGRectMake(0, 40, 0, 0);

pickerView = [[UIPickerView     alloc] initWithFrame:pickerFrame];
pickerView.showsSelectionIndicator = YES;
pickerView.dataSource = self;
pickerView.delegate = self;

[actionSheet addSubview:pickerView];
//[pickerView release];     

pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
pickerToolbar.barStyle = UIBarStyleBlackOpaque;
[pickerToolbar sizeToFit];

NSMutableArray *barItems = [[NSMutableArray alloc] init];   

UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];  
[barItems addObject:flexSpace];  

UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneButtonPressed:)];  
[barItems addObject:doneBtn];  

UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelButtonPressed:)];  
[barItems addObject:cancelBtn];  


[pickerToolbar setItems:barItems animated:YES];  

[actionSheet addSubview:pickerToolbar];  

[actionSheet addSubview:pickerView];  

[actionSheet showInView:self.view];  

[actionSheet setBounds:CGRectMake(0, 0, 320, 485)];         

}

When Done button in Tool bar pressed it will call this method

-(void)doneButtonPressed:(id)sender{  
//Do something here here with the value selected using [pickerView date] to get that value   
[actionSheet dismissWithClickedButtonIndex:1 animated:YES];   
[pickerView release];
[pickerToolbar release];
[actionSheet release];     
}  

Here is my questions

How to get The picker value from action sheet?

How to set that value to the button?

Thanks for your help guys


Solution

  • Assuming the pickerView datasource has only one component you can get the selected row using:

    NSInteger row = [pickerView selectedRowInComponent:0];