Search code examples
iosobjective-cuidatepicker

UIDatePicker get .date property on "done" button press


I have a custom view with a UIDatePicker and a done button attached at the top.

When I press the done button, I would like to get the time that is in the UIDatePicker.

I receive an error when I press the button (which I expect since the sender is a UIBarButtonItem) and changing the date time works as expected.

Other solutions show separate selectors but, I would like (if possible) to call the same selector and get the selected as if it were scrolling in the picker view.

I thought of changing the selector method to receive it as an id but, that did not work.

This is what I'm doing currently, I feel like it might be something silly:

UIView *v = [[UIView alloc] init];

// Create the date time picker
CGRect pickerFrame = CGRectMake(0, 0, 320, 216);
UIDatePicker *pView = [[UIDatePicker alloc] initWithFrame:pickerFrame];

pView.datePickerMode = UIDatePickerModeTime;
[pView addTarget:self action:@selector(dateTimePickerValueChanged:) forControlEvents:UIControlEventValueChanged];

dateTimePicker = pView;
[v addSubview:dateTimePicker];

// done button
CGRect toolBarFrame = CGRectMake(0, 0, 320, 44);
UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:toolBarFrame];
UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(dateTimePickerValueChanged:)];
NSArray *toolBarItems = [NSArray arrayWithObjects:flexibleItem, doneButton, nil];
[toolBar setItems:toolBarItems];
[v addSubview:toolBar];

- (void)dateTimePickerValueChanged:(UIDatePicker *)datePicker {
    NSLog(@"time on change: %@", datePicker.date);

Image reference:

enter image description here


Solution

  • Write your method without parameter and make your UIDatePicker as a property or global object for entire class so that you can access it from any where.

    Now pass your method to both selectors in this way you will achieve date on done button press.

    - (void)dateTimePickerValueChanged {
        NSLog(@"time on change: %@", datePicker.date);
    }