The UIDatePicker class implements an object that uses multiple rotating wheels to allow users to select dates and times. iPhone examples of a date picker are the Timer and Alarm (Set Alarm) panes of the Clock application. You may also use a date picker as a countdown timer.

When properly configured, a UIDatePicker object sends an action message when a user finishes rotating one of the wheels to change the date or time; the associated control event is UIControlEventValueChanged. AUIDatePicker object presents the countdown timer but does not implement it; the application must set up anNSTimer object and update the seconds as they’re counted down. Apple Documentation.

Steps:

  1. Create a new Xcode Project Lets say(DatePickerDemo).
  2. Go to storyboard and take  one datePicker, one toolbar and take one barbuttonitem on toolbar. Take one Button and two labels. StoryBoard will look something like this.

Screen Shot 2016-07-26 at 5.12.38 PM

  1.  Here I have given Button name as select date and toolbar button name as cancel and done.

  2. Make proper IBOutlet connection and action.

  3. Write the following code in your ViewController.m. Here I am setting the DatePickerMode as UIDatePickerModeDate, You can change it according to your need.

you can also set the maximum and minimum date for the date picker.

#import “ViewController.h”

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIDatePicker *datePicker;

@property (weak, nonatomic) IBOutlet UILabel *dateLabel;

@property (weak, nonatomic) IBOutlet UIToolbar *toolbar;

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    [self.datePicker setDatePickerMode:UIDatePickerModeDate];

    [self.datePicker setMaximumDate:[NSDate date]];

    self.toolbar.hidden = YES;

    self.datePicker.hidden = YES;

    self.dateLabel.hidden = YES;

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

#pragma marks – Action Methods

– (IBAction)toolBarCancelButtonAction:(id)sender {

    self.toolbar.hidden = YES;

    self.datePicker.hidden = YES;

    self.dateLabel.hidden = YES;

}

– (IBAction)toolBarDoneButtonAction:(id)sender {

    self.dateLabel.text = [NSString stringWithFormat:@”The chosen date is %@”,[_datePicker date]];

    self.toolbar.hidden = YES;

    self.datePicker.hidden = YES;

    self.dateLabel.hidden = NO;

}

– (IBAction)selectdateButtonAction:(id)sender {

    self.toolbar.hidden = NO;

    self.datePicker.hidden = NO;

    self.dateLabel.hidden = YES;

}

  1. Run Your code and see the desired output. You can download the whole source code from  here.  Please do share your reviews.

Enjoy Coding 🙂

Advertisements