tags:

views:

919

answers:

1

How can I implement a modal date picker?

What I want to happen is when the user enters a text field, a new view is created that has the date picker on it. From there, the user can interact and select a date. When the view is closed it should somehow return the date to it's caller. Is this possible?

BTW, I cannot put the date picker on my main form because of space.

Thanks in advance.

+6  A: 

Use a delegate!

Header:

@class DatePickerController;
@protocol DatePickerControllerDelegate
- (void) datePickerController:(DatePickerController *)controller didPickDate:(NSDate *)date;
@end

@interface DatePickerController : UIViewController {
  UIDatePicker *datePicker;
  NSObject <DatePickerControllerDelegate> *delegate;
}

@property (nonatomic, retain) UIDatePicker *datePicker;
@property (nonatomic, assign) NSObject <DatePickerControllerDelegate> *delegate;
@end

class:

@implementation DatePickerController
- (void) loadView {
  self.view = [[[UIView alloc] init] autorelease];
  self.datePicker = [[[UIDatePicker alloc] init] autorelease];
  [self.view addSubview:self.datePicker];
  UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  [button setTitle:@"Done" forState:UIControlStateNormal];
  button.center = CGPointMake(160,240);
  [button addTarget:self action:@selector(done) forControlEvents:(UIControlEventTouchUpInside)];
  [self.view addSubview:button];
}

- (void) done {
  [delegate datePickerController:controller didPickDate:datePicker.date];
}

- (void) dealloc {
  [datePicker release];
  [super dealloc];
}

@end

All that crap in loadView can be replaced with a NIB if you prefer. Just make sure to declare datePicker as an IBOutlet. And when you want to actually use it:

- (void) pickDate {
  DatePickerController *screen = [[[DatePickerController alloc] init] autorelease];
  screen.delegate = self;
  [self presentModalViewController:screen animated:YES];
}

- (void) datePickerController:(DatePickerController *)controller didPickDate:(NSDate *)date {
  [self doSomethingWithDate:date];
  [controller dismissModalViewControllerAnimated:YES];
}
Ed Marty
Great answer, Ed!
Typeoneerror
Hi Ed, bit of a newbie here, could you supply a working demo at all? Think i'm missing something!
jimbo
Sure... what's wrong with the code above? Is it not working? It should.
Ed Marty
I don't think there is anything wrong as such, I just can't seem to get it to work, but i could be putting things in the wrong places, knowing me... Simple working example would be great, as I can't find any examples on the net...
jimbo
Hi Ed, I am almost there... I have created a new post http://stackoverflow.com/questions/3820706/how-to-implement-a-modal-date-picker
jimbo