how to implement date picker on button click in ios?
-(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];
}
Try this:
- (IBAction)date:(id)sender {
datepicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 250, 325, 300)];
datepicker.datePickerMode = UIDatePickerModeDate;
datepicker.hidden = NO;
datepicker.date = [NSDate date];
[datepicker addTarget:self
action:@selector(labelChange:)
forControlEvents:UIControlEventValueChanged];
[self.view addSubview:datepicker]; //this can set value of selected date to your label change according to your condition
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"M-d-yyyy"]; // from here u can change format..
_selectedDate.text = [df stringFromDate:datepicker.date];
}
- (void)labelChange:(id)sender{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"M-d-yyyy"];
_selectedDate.text = [NSString stringWithFormat:@"%@",
[df stringFromDate:datepicker.date]];
[datepicker removeFromSuperview];
}