Show UIDatePicker on UITextField tap in Swift

This is quite a common usecase. You tap on a textfield that represents a time or a date and a related picker appears. I looked for a Beginner’s way to implement this feature by hand.

I combined a lot of tutorials and my own stuff to learn more about the connection between Storyboard actions and code-behind control flows. As a result, I got a tiny source snippet that provides all my required set of features.

Source code

class CreateSuggestionViewController : UIViewController {

    // 1
    @IBOutlet var dateField: UITextField!

    // 2
    let dateFormat: NSDateFormatter = NSDateFormatter()
    let datePicker: UIDatePicker = UIDatePicker()

    override func viewDidLoad() {
        super.viewDidLoad()

        // 3
        // Setup date picker
        dateFormat.dateStyle = NSDateFormatterStyle.ShortStyle
        dateFormat.timeStyle = NSDateFormatterStyle.ShortStyle
        datePicker.datePickerMode = UIDatePickerMode.DateAndTime
        datePicker.addTarget(self, action: Selector("updateDateField:"),

forControlEvents:UIControlEvents.ValueChanged) dateField.inputView = datePicker }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.toolbarHidden = false
    }

    // MARK: - Helpers

    // 4
    func updateDateField(sender: UIDatePicker) {
        dateField.text = dateFormat.stringFromDate(sender.date)
    }
}

You can find this code in action at my Github repository ‚nomster-ios‚.

Step-by-Step

  1. The dateField represents the UITextField representation of the date picker. In other words: It’s just a UITextField that is linked as a IBOutlet to the view controller.

  2. The datePicker and the dateFormat represents the non-Storyboard elements of the feature. That means, you don’t have to drag and drop an UIDatePicker into your Storyboard.

  3. The setup of the datePickerincludes the style settings, the picker mode which can be changed and a wired event listener which updates the (1.) date text field.

  4. The event listener listens on the valueChanged event of the (2.) UIDatePicker. If such an event is raised, the method will be set the formatted string value of the selected date as the value of the (1.) text field.

Screenshots

Schreibe einen Kommentar

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden / Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden / Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden / Ändern )

Google+ Foto

Du kommentierst mit Deinem Google+-Konto. Abmelden / Ändern )

Verbinde mit %s