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).

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"@interfaceViewController()@property(nonatomic,strong)UIDatePicker*myDatePicker;@end@implementationViewController...
And now let’s instantiate the date picker, as planned:
-(void)viewDidLoad{[superviewDidLoad];self.myDatePicker=[[UIDatePickeralloc]init];self.myDatePicker.center=self.view.center;[self.viewaddSubview:self.myDatePicker];}
Now let’s run the app and see how it looks in Figure 1-14.

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access