UIDatePicker in UIKit

UIDatePicker is a versatile component in the UIKit framework, providing a user interface element that allows users to select dates and times. In this article, we will explore what UIDatePickers are, the various functionalities they offer

article

UIDatePicker in UIKit


UIDatePicker is a versatile component in the UIKit framework, providing a user interface element that allows users to select dates and times. In this article, we will explore what UIDatePickers are, the various functionalities they offer, and provide practical code examples to demonstrate how you can implement and customize them in your iOS projects.


What is a UIDatePicker?


A UIDatePicker is a UIControl that provides a way for users to select dates and times. It displays a spinning wheel interface that users can interact with to choose specific dates, times, or both. UIDatePickers are commonly used in forms, calendars, scheduling applications, and any scenario where date and time selection is required.


What Can You Do with UIDatePickers?


UIDatePickers offer a range of functionalities and customization options. Here are some key things you can do with UIDatePickers:


  • Select Dates: Allow users to pick dates, including day, month, and year.
  • Select Times: Allow users to pick times, including hours and minutes.
  • Select Both Date and Time: Allow users to pick both date and time simultaneously.
  • Minimum and Maximum Dates: Set minimum and maximum allowable dates.
  • Custom Appearance: Customize the appearance of the date picker, including its mode and locale.
  • Respond to Value Changes: Use target-action methods to respond to date and time changes.

Implementing UIDatePicker in Swift


Let's dive into some code examples to see how you can create, customize, and work with UIDatePickers in Swift.


To create a simple UIDatePicker, you need to initialize it and add it to your view. Here is an example:


import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        // Create a UIDatePicker
        let datePicker = UIDatePicker()
        datePicker.datePickerMode = .date
        datePicker.center = view.center
        datePicker.addTarget(self, action: #selector(dateChanged(_:)), for: .valueChanged)
        datePicker.translatesAutoresizingMaskIntoConstraints = false

        // Add the date picker to the view
        view.addSubview(datePicker)

        // Set Auto Layout constraints
        NSLayoutConstraint.activate([
            datePicker.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            datePicker.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
    }

    @objc func dateChanged(_ sender: UIDatePicker) {
        print("Selected date: \(sender.date)")
    }
}

In this example, we create a UIDatePicker and set its mode to select dates only. The date picker is added to the view and centered using Auto Layout constraints. We also add a target-action method to handle value changes and print the selected date to the console.


Customizing UIDatePicker Appearance


You can customize the appearance of UIDatePicker to match the design of your application. Here is an example of customizing the date picker to show both date and time:


import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        // Create a UIDatePicker
        let datePicker = UIDatePicker()
        datePicker.datePickerMode = .dateAndTime
        datePicker.center = view.center
        datePicker.addTarget(self, action: #selector(dateChanged(_:)), for: .valueChanged)
        datePicker.translatesAutoresizingMaskIntoConstraints = false

        // Add the date picker to the view
        view.addSubview(datePicker)

        // Set Auto Layout constraints
        NSLayoutConstraint.activate([
            datePicker.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            datePicker.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
    }

    @objc func dateChanged(_ sender: UIDatePicker) {
        print("Selected date and time: \(sender.date)")
    }
}

In this example, we customize the UIDatePicker by setting its mode to select both date and time. This allows users to pick a specific date and time using the same control.


Setting Minimum and Maximum Dates


You can restrict the date range that users can select by setting minimum and maximum dates. Here is an example:


import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        // Create a UIDatePicker
        let datePicker = UIDatePicker()
        datePicker.datePickerMode = .date
        datePicker.center = view.center
        datePicker.addTarget(self, action: #selector(dateChanged(_:)), for: .valueChanged)
        datePicker.translatesAutoresizingMaskIntoConstraints = false

        // Set minimum and maximum dates
        let currentDate = Date()
        let calendar = Calendar.current
        var dateComponents = DateComponents()
        dateComponents.year = -1
        let minDate = calendar.date(byAdding: dateComponents, to: currentDate)
        dateComponents.year = 1
        let maxDate = calendar.date(byAdding: dateComponents, to: currentDate)

        datePicker.minimumDate = minDate
        datePicker.maximumDate = maxDate

        // Add the date picker to the view
        view.addSubview(datePicker)

        // Set Auto Layout constraints
        NSLayoutConstraint.activate([
            datePicker.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            datePicker.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
    }

    @objc func dateChanged(_ sender: UIDatePicker) {
        print("Selected date: \(sender.date)")
    }
}

In this example, we set the minimum and maximum dates of the UIDatePicker to one year before and one year after the current date. This restricts the selectable dates within the specified range.


Using UIDatePicker with Different Locales


You can customize the locale of the UIDatePicker to match the user's region and language preferences. Here is an example:


import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        // Create a UIDatePicker
        let datePicker = UIDatePicker()
        datePicker.datePickerMode = .date
        datePicker.center = view.center
        datePicker.addTarget(self, action: #selector(dateChanged(_:)), for: .valueChanged)
        datePicker.translatesAutoresizingMaskIntoConstraints = false

        // Set the locale
        datePicker.locale = Locale(identifier: "fr_FR")

        // Add the date picker to the view
        view.addSubview(datePicker)

        // Set Auto Layout constraints
        NSLayoutConstraint.activate([
            datePicker.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            datePicker.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
    }

    @objc func dateChanged(_ sender: UIDatePicker) {
        print("Selected date: \(sender.date)")
    }
}

In this example, we set the locale of the UIDatePicker to French (France). This customizes the date picker to display dates in the format and language appropriate for that locale.


Handling Different Date Picker Modes


UIDatePicker provides several modes that determine what kind of date or time information it displays. Here are the different modes you can set:


  • .time: Displays hours and minutes.
  • .date: Displays day, month, and year.
  • .dateAndTime: Displays both date and time.
  • .countDownTimer: Displays a countdown timer in hours and minutes.

Here is an example of using UIDatePicker in different modes:


import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        // Create a UIDatePicker for time
        let timePicker = UIDatePicker()
        timePicker.datePickerMode = .time
        timePicker.center = CGPoint(x: view.center.x, y: view.center.y - 100)
        timePicker.addTarget(self, action: #selector(timeChanged(_:)), for: .valueChanged)
        timePicker.translatesAutoresizingMaskIntoConstraints = false

        // Create a UIDatePicker for date
        let datePicker = UIDatePicker()
        datePicker.datePickerMode = .date
        datePicker.center = CGPoint(x: view.center.x, y: view.center.y)
        datePicker.addTarget(self, action: #selector(dateChanged(_:)), for: .valueChanged)
        datePicker.translatesAutoresizingMaskIntoConstraints = false

        // Create a UIDatePicker for date and time
        let dateTimePicker = UIDatePicker()
        dateTimePicker.datePickerMode = .dateAndTime
        dateTimePicker.center = CGPoint(x: view.center.x, y: view.center.y + 100)
        dateTimePicker.addTarget(self, action: #selector(dateTimeChanged(_:)), for: .valueChanged)
        dateTimePicker.translatesAutoresizingMaskIntoConstraints = false

        // Add the date pickers to the view
        view.addSubview(timePicker)
        view.addSubview(datePicker)
        view.addSubview(dateTimePicker)
    }

    @objc func timeChanged(_ sender: UIDatePicker) {
        print("Selected time: \(sender.date)")
    }

    @objc func dateChanged(_ sender: UIDatePicker) {
        print("Selected date: \(sender.date)")
    }

    @objc func dateTimeChanged(_ sender: UIDatePicker) {
        print("Selected date and time: \(sender.date)")
    }
}

In this example, we create three different UIDatePickers, each configured with a different mode (.time, .date, and .dateAndTime). Each date picker is positioned at different points in the view, and target-action methods handle their value changes.


Conclusion


UIDatePickers are powerful tools for date and time selection in your iOS applications. In this article, we've covered the basics of what UIDatePickers are, their various functionalities, and provided practical code examples to help you implement and customize them in your own projects. From creating simple date pickers to customizing their appearance and handling different date picker modes, mastering UIDatePickers is essential for building intuitive and user-friendly interfaces.


Understanding and effectively utilizing UIDatePickers can significantly enhance your app's usability and user experience. Experiment with different UIDatePicker properties and techniques to create dynamic and engaging date and time selectors in your iOS applications.

instructor

Exodai INSTRUCTOR!

Johan t'Sas

Owner and Swift developer!