DatePicker in SwiftUI
Introduction
Pre-requisite for SwiftUI development :-
- Xcode 11
- MacOS Catalina 10.15.2
Getting Started
DatePicker is a control for selecting an absolute date. In SwiftUI The date picker provides a custom Picker View that uses multiple rotating wheels to allow users to select dates and times.
- Create a DatePicker
- Create a TimePicker
- Combination of DatePicker & TimePicker
Application Entry Point
Creating a New Project for Playing with SwiftUI. First, fire up Xcode and create a new Project. I created a project named DemoDatePicker.
Once you save the project, Xcode should load the ContentView.swift file and display a design/preview canvas.
By default, Xcode generates some SwiftUI code for ContentView.swift. However, the preview canvas doesn’t render the app preview. You have to click the Resume button in order to see the preview.
Create a DatePicker
We can create a basic DatePicker by set .displayedComponent: .date
like this:
@State private var pickerDate = Date()var body: some View {
VStack {
DatePicker("Picker", selection: $pickerDate, displayedComponents: .date)
}}
If you want to hide the DatePicker label, you can use labelsHidden() property like this:
DatePicker("Picker", selection: $pickerDate, displayedComponents: .date).labelsHidden()
Create a TimePicker
We can create a basic DatePicker by set .displayedComponent: .hourAndMinute
like this:
DatePicker("Picker", selection: $pickerDate, displayedComponents: .hourAndMinute)
Combination of DatePicker & TimePicker
You need both TimePicker and DatePicker .displayedComponent
could actually take an array. By including both time and date, you will get both DatePicker and TimePicker.
DatePicker("Date and Time Picker", selection: $pickerDate, displayedComponents: [.date, .hourAndMinute])
If you want to set maximum and minimum date, you can use ClosedRange.
private var dateClosedRange: ClosedRange<Date> {
let min = Calendar.current.date(byAdding: .day, value: -1, to: Date())!
let max = Calendar.current.date(byAdding: .day, value: 1, to: Date())!
return min...max
}DatePicker("Picker with minimum and maximum date", selection: $pickerDate, in: dateClosedRange, displayedComponents: [.date, .hourAndMinute])
Conclusion
I hope you enjoyed reading this. In this tutorial, we got an introduction about the DatePicker control of SwiftUI.
Please find the Github link.
Github:- https://github.com/imrishuj/SU-DatePicker
Thanks for reading and good luck with your next SwiftUI Tutorial!