Search code examples
xcode4ios5uidatepickeruiactionsheet

UIDatePicker, UIActionSheet, and Data handling


So I understand how to pull the date from a date picker just fine. But I can't seem to be able to pull it from a date picker on a UIActionSheet. Our current set up is a form for entering data with a few pickers, all using the didSelectRow method for the data source, all of them using the same view for said data source.

Now this doesn't work for a UIDatePicker in the same way, it seems. Here is what I have so far for my date picker, it's similar to my other pickers, including the methods to handle changing of values.

-(IBAction)ageBox{
    pickerAction=[[UIActionSheet alloc]initWithTitle:nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
    [pickerAction setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
    CGRect pickerFrame = CGRectMake(0, 40, 0, 0);

    UIDatePicker *datePicker =[[UIDatePicker alloc]initWithFrame:pickerFrame];

    [pickerAction addSubview:datePicker];

    UISegmentedControl *closeButton=[[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObject:@"OK"] ];
    closeButton.momentary = YES;
    closeButton.frame=CGRectMake(260, 7.0f, 50.0f, 30.0f);
    closeButton.segmentedControlStyle =UISegmentedControlStyleBar;
    closeButton.tintColor = [UIColor blackColor];
    date = datePicker.date;
    [closeButton addTarget:self action:@selector(closePicker) forControlEvents:UIControlEventValueChanged];
    [pickerAction addSubview:closeButton];
    whatToChange = 5;
    [pickerAction showInView:self.view];
    [pickerAction setBounds:CGRectMake(0, 0, 320, 464)];
}

Any help pulling the date from the date picker while it's on the action sheet, or when I click ok, pulling it from it before it's destroyed?


Solution

  • I'm making the assumption that pickerAction is an ivar of self, based on the first line of code in the method. I can think of a couple of ways, I'm sure there are more.

    1) Make datePicker an ivar as well. That way you have a reference to it for your 'ok' method.

    2) Obtain the reference from the pickerAction itself. Since you have added the datePicker as a subview, you can find it like so:

        // Somewhere in your "ok" method
        for (UIView *view in pickerAction.subviews) {
            if ([view isKindOfClass:[UIDatePicker class]]){
                UIDatePicker *picker = (UIDatePicker *)view;
                NSDate *pickedDate = picker.date;
            }
        }