In this tutorial, we’ll be discussing the UIDatePicker class and implement its various use cases in our iOS Application.
UIDatePicker
UIDatePicker class is a subclass of the UIPickerView. UIDatePicker control is used to display and select date and time values from the PickerView.
A UIDatePicker consists of multiple components for the date, time, seconds etc.
We can specify the timeInterval between consecutive rows.
Following are the four major modes of UIDatePicker:
- date
- dateAndTime – default
- time
- countDownTimer
We can set the mode on the UIDatePicker either from the Interface Builder or by using the property datePickerMode
.
We can also configure the locale, timezone.
The date
property represents the currently selected date in the UIDatePicker.
We can set the minimumDate
and maximumDate
properties from the interface builder or by using the equivalent properties in the Swift class.
Using the NSDateFormatter
or NSCalendar
class we can format the date returned from the UIDatePicker.
minuteInterval
property is used to set the time interval.
We can create an IBAction in the ViewController from the Interface Builder. The IBAction method would get triggered when an event occurs in the UIDatePicker. The event is generally valueChanged:
@IBAction func doSomething(sender: UIDatePicker, forEvent event: .valueChanged)
To connect it from the Interface Builder to the Swift class, we simply Ctrl + drag and drop. It opens a dialog like this:
If the miniumDate is greater than the maximumDate, then the default dates would be returned.The UIDatePickerView
can show dates beyond the minimumDate
specified. BUT once you leave the touch control, the UIDatePickerView would slide back to the minimumDate.
In order to change the background of the UIDatePickerView, we simply use the backgroundColor
property.
There are no public properties for the textColor. But we can always change them using there key.
datePicker.setValue(UIColor.brown, forKey: "textColor")
In order to disable the current highlighted date, we can set the following attribute to false:
datePicker.setValue(false, forKey: "highlightsToday")
In the following section, we’ll create the UIDatePickerView
in two ways and format the dates to be displayed in the UILabel
and UITextField
Project Storyboard
Code
The code for the ViewController.swift file is given below:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myDatePicker: UIDatePicker!
@IBOutlet weak var labelTwo: UILabel!
@IBOutlet weak var labelOne: UILabel!
@IBOutlet weak var myTextField: UITextField!
let datePicker = UIDatePicker()
@IBAction func dateMode(_ sender: Any) {
datePicker.datePickerMode = .date
}
@IBAction func timeMode(_ sender: Any) {
datePicker.datePickerMode = .time
}
@IBAction func countdownMode(_ sender: Any) {
datePicker.datePickerMode = .countDownTimer
}
override func viewDidLoad() {
super.viewDidLoad()
myDatePicker.addTarget(self, action: #selector(ViewController.datePickerValueChanged(_:)), for: .valueChanged)
createDatePicker()
createToolbar()
}
func createDatePicker()
{
datePicker.datePickerMode = .dateAndTime
datePicker.backgroundColor = .white
datePicker.minuteInterval = 30
datePicker.setValue(UIColor.brown, forKey: "textColor")
myTextField.inputView = datePicker
}
func createToolbar()
{
let toolBar = UIToolbar()
toolBar.barStyle = .default
toolBar.isTranslucent = true
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(ViewController.doneClick))
toolBar.setItems([doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
myTextField.inputAccessoryView = toolBar
}
@objc func doneClick() {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .medium
myTextField.text = dateFormatter.string(from: datePicker.date)
myTextField.resignFirstResponder()
}
@objc func datePickerValueChanged(_ sender: UIDatePicker){
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy hh:mm a"
let selectedDate: String = dateFormatter.string(from: sender.date)
labelOne.text = selectedDate
let components = Calendar.current.dateComponents([.year, .month, .day], from: sender.date)
if let day = components.day, let month = components.month, let year = components.year {
labelTwo.text = "Day: (day) Month: (month) Year: (year)"
}
}
}
In the above code, we’ve created a UIDatePicker in the Storyboard, and another programmatically.
The programmatically one displays the date formatted in the UITextField.
The UIDatePicker from the Storyboard displays the date using NSDateFormatter
and Calendar
classes in each of the UILabel
.
We’ve set the minuteInterval
to 30 minutes.
Instead of creating an IBAction, we’ve done the same programmatically using addTarget
The output of the application in action is :
This brings an end to this tutorial. You can download the project from the link below: