iOS Swift UIDatePicker with Done and Cancel Buttons programmatically

You can use a date picker to allow a user to select a date, time value or both). You can also use it as a timer or stop clock. The date picker reports interactions to its associated target object.

UIDatePicker has various picker modes

  • Time - The date picker displays hours, minutes, and (optionally) an AM/PM designation.
  • Date - The date picker displays months, days of the month, and years.
  • DateAndTime - The date picker displays both Date and Time.
  • CountDownTimer - The date picker displays hour and minute values, for example [ 2 | 59 ]. 

        //Create a DatePicker
        let datePicker: UIDatePicker = UIDatePicker()
        //Position date picker within a view
        datePicker.frame = CGRect(x: 10, y: 50, width: self.view.frame.width, height: 200)
        //Set Mode for Picker
        datePicker.datePickerMode = .dateAndTime
        //Set some of UIDatePicker properties
        datePicker.timeZone = NSTimeZone.local
        datePicker.backgroundColor = UIColor.white
        //Set minimum and Maximum Dates
        let calendar = Calendar(identifier: .gregorian)
        var comps = DateComponents()
        comps.month = 1
        let maxDate = comps, to: Date())
        comps.month = 0 = -1
        let minDate = comps, to: Date())
        datePicker.maximumDate = maxDate
        datePicker.minimumDate = minDate
        //add the picker to view

Now lets create a Date Picker with Done and Cancel Buttons using a UIToolbar

iOS Swift UIDatePicker

iOS Swift UIDatePicker with Done and Cancel Buttons

iOS Swift UIDatePicker UITextField

import UIKit

class ViewController: UIViewController {

    var pickerToolbar: UIToolbar?
    var dateTextField: UITextField?
    var datePicker = UIDatePicker()
    override func viewDidLoad() {
        self.navigationItem.title = "Main View"
        //create the UITextfield to present the Date Picker
        //create the Toolbar for Cancel and Done buttons
        //set date picker mode
        datePicker.datePickerMode = .date
        //add toolbar to textField
        dateTextField?.inputAccessoryView = pickerToolbar
        //add datepicker to textField
        dateTextField?.inputView = datePicker
    func createUITextField(){
        let myLabel = UILabel()
        myLabel.textColor =
        myLabel.text = "Date: "
        myLabel.font = UIFont.systemFont(ofSize: 24.0)
        myLabel.translatesAutoresizingMaskIntoConstraints = false
        let myLabel2 = UILabel()
        myLabel2.textColor = UIColor.brown
        myLabel2.text = " (MM/DD/YY) "
        myLabel2.font = UIFont.systemFont(ofSize: 24.0)
        myLabel2.translatesAutoresizingMaskIntoConstraints = false
        dateTextField = UITextField()
        dateTextField?.text = "Select a date ..."
        dateTextField?.textColor =
        dateTextField?.font = UIFont.systemFont(ofSize: 24.0)
        dateTextField?.layer.borderColor = UIColor.lightGray.cgColor
        dateTextField?.layer.borderWidth = 1.0
        dateTextField?.layer.cornerRadius = 3;
        dateTextField?.translatesAutoresizingMaskIntoConstraints = false
        var allConstraints: [NSLayoutConstraint] = []
        let views = ["view": view!, "myLabel": myLabel, "dateTextField": dateTextField, "myLabel2": myLabel2]
        let horizontalConstraints = NSLayoutConstraint.constraints(
            withVisualFormat: "H:|-[myLabel]-[dateTextField(200)]-[myLabel2]-(>=10)-|",
            options: [.alignAllTop, .alignAllBottom], metrics: nil, views: views as [String : Any])
        allConstraints += horizontalConstraints
        var verticalConstraints = NSLayoutConstraint.constraints(
            withVisualFormat: "V:|-(>=40)-[myLabel]", metrics: nil, views: views as [String : Any])
        allConstraints += verticalConstraints
        verticalConstraints = NSLayoutConstraint.constraints(
            withVisualFormat: "V:|-(>=40)-[dateTextField]", metrics: nil, views: views as [String : Any])
        allConstraints += verticalConstraints
        verticalConstraints = NSLayoutConstraint.constraints(
            withVisualFormat: "V:|-(>=40)-[myLabel2]", metrics: nil, views: views as [String : Any])
        allConstraints += verticalConstraints
    func createUIToolBar() {
        pickerToolbar = UIToolbar()
        pickerToolbar?.autoresizingMask = .flexibleHeight
        //customize the toolbar
        pickerToolbar?.barStyle = .default
        pickerToolbar?.barTintColor =
        pickerToolbar?.backgroundColor = UIColor.white
        pickerToolbar?.isTranslucent = false
        //add buttons
        let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action:
        cancelButton.tintColor = UIColor.white
        let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action:
        doneButton.tintColor = UIColor.white
        //add the items to the toolbar
        pickerToolbar?.items = [cancelButton, flexSpace, doneButton]
    @objc func cancelBtnClicked(_ button: UIBarButtonItem?) {
    @objc func doneBtnClicked(_ button: UIBarButtonItem?) {
        let formatter = DateFormatter()
        formatter.dateStyle = .short
        dateTextField?.text = formatter.string(from:

Click here for more information on Swift Date formatting and conversion

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.