Archive for 21st November 2010

iPhone date and time picker view

I was looking around for a view that somebody had previously put together to show a modal view to allow the selection of a date and time, and found nothing.  This seemed like something reasonable to expect to find.  Apparently, none of the umpteen thousand fart application developers have ever had a need to create a date and time picker view, or if they did, they did not feel the need to share their creation with the world at large.

So here it is.  This is what it looks like when you use it in your application:

Here is the code that you would use to instantiate the view in your parent view controller, where selectedDate is the default date that you want the view to display when it opens up:

DateTimePicker *controller = [[DateTimePicker alloc] init];
controller.delegate = self;
controller.defaultDate = selectedDate;
[self presentModalViewController:controller animated:YES];
[controller release];

To receive messages back from this modal view, you just need your parent view to follow the DateTimePickerDelegate delegate, which means you would need to have the dateTimePickerOK and dateTimePickerOK methods in your parent view.  These methods are called when the user taps the Save or Cancel buttons respectively on the modal view.  Here is what those methods could look like:

- (void)dateTimePickerOK:(DateTimePicker *)controller didPickDate:(NSDate *)date
{
    self.selectedDate = date;
    [self redrawDate];
 
    [controller dismissModalViewControllerAnimated:YES];
}
 
- (void)dateTimePickerCancel:(DateTimePicker *)controller
{
    [controller dismissModalViewControllerAnimated:YES];
}

I have put together a sample application that demonstrates the use of the date and time picker view, which also of course includes the DateTimePicker header, implementation, and NIB files.  Please feel free to use these in our own code, and if you make any cool changes to it, please let me know so that I might include them in my example or ridicule you in the posting comments.

The sample code zip file is here:

DatePickerExample