Use datepicker as input to uitextfield in swift

This tutorial is updated for X code 7.3 & swift 2.2

This is very commonly used in many iOS apps. Instead of keyboard popping up when you click on text field, the datepicker pops up. And you can select date to be added to the textfield.

1. Open x code & create new single view application project. Set values as follows & save it on desktop.

new x code project


2. Go to main storyboard & select view controller. In attributes section set size to iPhone 4”

iPhone size 4 inches


3. Add textfield to view controller and set width to 175

textfield width


4. Open assistant editor and add textfield as outlet

textfield as outlet


5. Again add textfield as action & make sure to set “Event” to “Editing Did Begin”

textField as action


6. Add this code inside the textfield action

    @IBAction func textFieldEditing(sender: UITextField) {
        // 6
        let datePickerView:UIDatePicker = UIDatePicker()
        datePickerView.datePickerMode = UIDatePickerMode.Date
        sender.inputView = datePickerView
        datePickerView.addTarget(self, action: #selector(ViewController.datePickerValueChanged), forControlEvents: UIControlEvents.ValueChanged)

This code will initialise datepicker & set its mode to select date. After that set datepicker as textfields input view.

7. Then you have to add code that will trigger method when datepicker value is changed. Add following method

    // 7
    func datePickerValueChanged(sender:UIDatePicker) {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
        dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
        dateTextField.text = dateFormatter.stringFromDate(

This will update textfields text with value of datepicker. Now run the project in iPhone 5s.

datepicker as input to textfield

Download X Code file
Challenge: Add bar at the top of date picker with two buttons & label as follows.

toobar to datepicker

Download Challenge Solution
Total 63 Votes

Tell us how can I improve this tutorial?

+ = Verify Human or Spambot ?