Add Done Button On UIDatePicker

by sisccr

Default UIDatePicker View has a default Done button when it is displayed. But It does not work by default.


If you are using the textField delegate, It is simple. Ios provides us a delegate function that is called when Return key is pressed.

func textFieldShouldReturn(textField: UITextField) -> Bool {
    // done button clicked

But my requirement don’t allows us to use delegate, so I need another way.

So, we need to add an button. I will be adding button pragmatically but we can also use the storyboard.

I already have textField which shows datePicker when selected.

after setting up the textField and datePicker, a function is called to add the “Done” button.

    func setUpDoneButton() {
        let toolBar = UIToolbar()
        toolBar.barStyle = .Default
        toolBar.translucent = true
        let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
        let doneButton = UIBarButtonItem(title: "Done", 
                                         style: .Done, 
                                         target: self, 
                                         action: #selector(doneDatePickerPressed(_:)))
        doneButton.tintColor = UIColor.blackColor()
        toolBar.setItems([space, doneButton], animated: false)
        toolBar.userInteractionEnabled = true

after setting up the button addDoneButtonToDatePickers function is called.

func addDoneButtonToDatePickers(doneButton: UIToolbar) {
        addDoneButtonToDatePickerView(txtStartDate, doneButton: doneButton)
        addDoneButtonToDatePickerView(txtEndDate, doneButton: doneButton)
func addDoneButtonToDatePickerView(textField: UITextField, doneButton: UIToolbar) {
        textField.inputAccessoryView = doneButton

When Done button is touched, doneDatePickerPressed function is called.

    func doneDatePickerPressed(sender: UIBarButtonItem) {
        print("done button clicked.")