Marcos Samuel Dávalos Marcos Samuel Dávalos - 4 months ago 25
iOS Question

UIDatePicker with "done" button

I need to add a "done" button to my date picker like in this image:

enter image description here

This is my code:

-(IBAction)chooseDate:(id)sender{
self.datepicker= [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 320, 216)];
self.datepicker.datePickerMode = UIDatePickerModeDate;
datepicker.backgroundColor = Rgb2UIColor(52, 170, 220);

[self.btnDone
addTarget:self
action:@selector(SetDatePickerTime:)
forControlEvents:UIControlEventTouchDown];

[self.view addSubview:self.datepicker];
}

Answer

Create a date picker, then add it as the input view of the field in question (self.fieldInQuestion.inputView = datePicker). Next, create a UIToolBar (height 44) with UIBarButton Item on it with the title "Done", target of self, and a selector (ex. @selector(done)). Add this as the input accessory view of the same field you made the date picker an input view for (self.fieldInQuestion.inputAccessoryView = UIToolbarInstance). In the selector method (-(void)done in the example above), make sure you use [self.fieldInQuestion resignFirstResponder] and it will dismiss it.

Comments