how to implement date picker on button click in ios?

Daljeet picture Daljeet · Nov 7, 2014 · Viewed 37.5k times · Source

I am building an iOS app.I am using storyboards to build the screens and i have made a form which contain some fields like Name,Date,min and max.

I am facing an problem that is not able to implement date picker on button click and when user select the date,date picker hide,want to display selected date in a label.

I googled but could not find a good tutorial or library. I want to show only days and date in picker.

Answer

iosDev picture iosDev · Jan 6, 2015
-(IBAction)datePickerBtnAction:(id)sender
{
    datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 0,10, 50)];
    datePicker.datePickerMode = UIDatePickerModeDate;
    datePicker.hidden = NO;
    datePicker.date = [NSDate date];
    [datePicker addTarget:self action:@selector(labelTitle:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:datePicker];
    rightBtn = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(save:)];
    self.navigationItem.rightBarButtonItem = rightBtn;       
}

-(void)labelTitle:(id)sender
{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
    dateFormat.dateStyle = NSDateFormatterMediumStyle;
    [dateFormat setDateFormat:@"MM/dd/yyyy"];
    NSString *str = [NSString stringWithFormat:@"%@",[dateFormat  stringFromDate:datePicker.date]];
    //assign text to label
    label.text=str; 
}

-(void)save:(id)sender
{
    self.navigationItem.rightBarButtonItem = nil;
    [datePicker removeFromSuperview];       
}