UIDatePicker with UIToolbar

Thlbaut picture Thlbaut · Jun 19, 2015 · Viewed 7.8k times · Source

I'm trying to implement UIToolbar on UIDatepicker to dismiss it when touching "Done" button. But when I tap on the button, the datepicker is scrolling and the action button doesn't work.

Here is my code :

datepicker = [[UIDatePicker alloc] initWithFrame:CGRectZero];
[datepicker setDatePickerMode:UIDatePickerModeDate];
[datepicker addTarget:self action:@selector(changeDate:) forControlEvents:UIControlEventValueChanged];

UIToolbar *toolbar= [[UIToolbar alloc] initWithFrame:CGRectMake(0,0,self.view.frame.size.width,44)];
toolbar.barStyle = UIBarStyleDefault;
UIBarButtonItem *flexibleSpaceLeft = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem* doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(dismiss)];

[toolbar setItems:[NSArray arrayWithObjects:flexibleSpaceLeft, doneButton, nil]];
[datepicker addSubview:toolbar];

My datepicker :

UIDatePicker

Thank you for your help.

Answer

oldrinmendez picture oldrinmendez · Jun 19, 2015

If you use UITextField set

textField.inputAccessoryView = toolbar;
textField.inputView = datepicker;