Skip to content

A 1.5. Picking the Date and Time with UIDatePicker

rayastar edited this page Feb 7, 2015 · 1 revision

Then we’ll allocate and initialize this property and add it to the view of our view controller:

#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,strong) UIDatePicker *myDatePicker;
@end

And now let’s instantiate the date picker, as planned:

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.myDatePicker = [[UIDatePicker alloc] init];
    self.myDatePicker.center = self.view.center;
    [self.view addSubview:self.myDatePicker];
 }

This mode can be changed through the datePickerMode property, which is of type UIDate PickerMode:

typedef NS_ENUM(NSInteger, UIDatePickerMode) {
    UIDatePickerModeTime,
    UIDatePickerModeDate,
    UIDatePickerModeDateAndTime,
    UIDatePickerModeCountDownTimer,
};

Just like the UISwitch class, a date picker sends action messages to its targets whenever the user has selected a different date. To respond to these messages, the receiver must add itself as the target of the date picker, using the addTarget:action:forControlE vents: method, like so:

- (void) datePickerDateChanged:(UIDatePicker *)paramDatePicker{
    if ([paramDatePicker isEqual:self.myDatePicker])
    {
        NSLog(@"Selected date = %@", paramDatePicker.date);
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.myDatePicker = [[UIDatePicker alloc] init];
    self.myDatePicker.center = self.view.center;
    [self.view addSubview:self.myDatePicker];
    [self.myDatePicker    addTarget:self
                          action:@selector(datePickerDateChanged:)
                          forControlEvents:UIControlEventValueChanged];

 }

A date picker also lets you set the minimum and the maximum dates that it can display. For this, let’s first switch our date picker mode to UIDatePickerModeDate and then, using the maximumDate and the minimumDate properties, adjust this range:

- (void)viewDidLoad
{
    [super viewDidLoad];
	self.myDatePicker = [[UIDatePicker alloc] init];
    self.myDatePicker.center = self.view.center;
    self.myDatePicker.datePickerMode = UIDatePickerModeDate;
    [self.view addSubview:self.myDatePicker];



    NSTimeInterval oneYearTime = 365*24*60*60;
    NSDate *todayDate = [NSDate date];

    NSDate *oneYearFromToday = [todayDate
                                dateByAddingTimeInterval:oneYearTime];
    NSDate *twoYearsFromToday = [todayDate
                                dateByAddingTimeInterval:2 * oneYearTime];

    self.myDatePicker.minimumDate = oneYearFromToday;
    self.myDatePicker.maximumDate = twoYearsFromToday;


    [self.myDatePicker addTarget:self
                       action:@selector(datePickerDateChanged:)
                       forControlEvents:UIControlEventValueChanged];
}
Clone this wiki locally