O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

1.5. Picking the Date and Time with UIDatePicker

Problem

You want to allow the users of your app to select a date and time using an intuitive and ready-made user interface.

Solution

Use the UIDatePicker class.

Discussion

UIDatePicker is very similar to the UIPickerView class. The date picker is in fact a prepopulated picker view. A good example of the date picker control is in the Calendar app on the iPhone (Figure 1-13).

A date picker shown at the center of the screen

Figure 1-13. A date picker shown at the center of the screen

Let’s get started by first declaring a property of type UIDatePicker. 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

@implementation ViewController

...

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];
}

Now let’s run the app and see how it looks in Figure 1-14.

A simple date picker

Figure 1-14. A simple date picker

You can see that the date picker, by default, has picked today’s date. The first thing that we need to know about date pickers is that they can have different styles or modes. This mode can be changed through the datePickerMode property, which is of type UIDatePickerMode:

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

Depending on what you need, you can set the mode of your date picker to any of the values listed in the UIDatePickerMode enumeration. I’ll show some of these as we go along.

Now that you have successfully displayed a date picker on the screen, you can attempt to retrieve its currently selected date using its date property. Alternatively, you can call the date method on the date picker, like so:

NSDate *currentDate = self.myDatePicker.date;
NSLog(@"Date = %@", currentDate);

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:forControlEvents: 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];

}

Now, every time the user changes the date, you will get a message from the date picker.

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;
}

With these two properties, we can then limit the user’s selection on the date to a specific range, as shown in Figure 1-15. In this example code, we have limited the user’s input of dates to the range of one year to two years from now.

Minimum and maximum dates applied to a date picker

Figure 1-15. Minimum and maximum dates applied to a date picker

If you want to use the date picker as a countdown timer, you must set your date picker mode to UIDatePickerModeCountDownTimer and use the countDownDuration property of the date picker to specify the default countdown duration. For instance, if you want to present a countdown picker to the user and set the default countdown duration to two minutes, write code like this:

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

    NSTimeInterval twoMinutes = 2 * 60;
    [self.myDatePicker setCountDownDuration:twoMinutes];
}

The results are shown in Figure 1-16.

A two-minute countdown duration set on a date picker

Figure 1-16. A two-minute countdown duration set on a date picker

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required