Storyboard application using Swift.
How can I close the calendar (presented for date selection when the UIDatePicker style is .compact) after a user selects a date? Currently, the user is required to tap outside the calendar for it to close. I want it to close automatically after a user has selected a date.
I've tried resigning first responder of the UIDatePicker, ending editing in the table view controller once a notification is received that a date changed, reading another response (here) and so far nothing is working for me.
There are now some choices other than just the slot machine-style wheels! Since iOS 2.0, the original style of UIDatePicker has been the only standard UIKit option for developers looking to let users select dates and times.
Setting UIDatePicker Style The new UIDatePickerStyle enum has four options: wheels – Shows the standard, spinning wheel style picker. (iOS 13.4+) compact – Displays a formatted label that will show a popover with more UI when tapped. (iOS 13.4+)
If you want to use the compact style, it’s just a different value for preferredDatePickerStyle. The compact style will initially present UI that looks like this. When the user taps on the date or the time in this case, the entire calendar and time control combination appears in a popover window.
One of the nice new features that came out with iOS 14 were some new options around the venerable UIDatePicker. There are now some choices other than just the slot machine-style wheels! Since iOS 2.0, the original style of UIDatePicker has been the only standard UIKit option for developers looking to let users select dates and times.
For now, you can do:
presentedViewController?.dismiss(animated: true, completion: nil)
i.e.
override func viewDidLoad() {
super.viewDidLoad()
datePicker.addTarget(self, action: #selector(dateChanged), for: .valueChanged)
}
@objc private func dateChanged() {
presentedViewController?.dismiss(animated: true, completion: nil)
}
But note that this will potentially break in future iOS versions as this relies on the implementation detail that compact
date pickers presents a view controller to show the calendar. If you print out the type of the presented VC, you'll see _UIDatePickerIOSCompactViewController
. The leading _
suggests that this is an implementation detail.
All that is documented about compact
is:
A style indicating that the date picker displays as a label that when tapped displays a calendar-style editor.
So in future versions of iOS, they could instead change the implementation to not present a new view controller, and this could very well break, and you'll have to find another way then. I see no documented way of doing this right now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With