DatePicker is a control used in iOS applications to get the date and time values from the user. We can allow the user to either enter the time in point or time interval.
Use the following steps to add the DatePicker to the interface.
- Set the UIView, i.e. (label, text field, button, etc.) to which you want to get the date and time from the user.
- Search for DatePicker in the object library and drag the result to the storyboard.
- Set the date picker mode
- Supply additional configuration options such as minimum and maximum dates if required.
- Create an action outlet for the date picker.
- Set up auto-layout rules for datepicker to set the position on different devices.
The datepicker is only used for the selection of date and time from the list.
In this example, we will create a text field in which we will allow a user to enter a date by selecting any date from the date picker.
To add the datepicker to the storyboard, we will search for the datepicker in the object library and drag the result into the storyboard.
The following image shows the interface builder; we created in the example. We have created the outlet for the text field and datepicker in the ViewController.swift file.
In ViewController.swift, we have just assigned the inputView property of the input text field to the datepicker, and the action connection of the datepicker is triggered each time when the value of datepicker is changed, which sets the text field text to the datepicker date. In this example, we have set the datepicker mode to date; however, we can set it to dateAndTime, or time to get the appropriate datetime or time values.
Interface Builder Attributes
||It represents the DatePicker Mode. It is used to determine whether the datepicker is going to display the date, time, date and time, or a countdown interval. This can be accessed at runtime using datePickerMode property.
||This represents the locale associated with the datepicker. This property overrides the system default locale. This can be accessed at runtime using the local property.
||It represents the granularity of the minute's spinner. The default value is 1, and the maximum value is 30. This value must be a divisor of 60. It can be accessed at runtime using minuteInterval property.
||It represents the date that the date picker is going to display initially. We can set this property at runtime.
||It represents the range of the dates that can be selected. We can configure the minimumDate and maximumDate property to configure the range.
||It is the initial value of the datepicker when it is shown in countdown timer mode.