Open UIDatePicker programmatically in iOS 14

I have this normal UIDatePicker (sorry that it's not in English, please ignore that):

my date picker

But the problem is that it only appears when I'm pressing the Date Picker:

image

And I wanted to know how to show the Date Picker like in the first image (that it's covering all the screen with the blur effect) only with code, so the user won't need to press the Date Picker to show the date selector. Thanks.


Solution 1:

You can use a datePicker with .compact style and put a UILabel on top of it and give it a background color to hide the datePicker behind it, and make sure the label user interaction is disabled then you should be able to tap on the datePicker and it will show the modal and then the value changed of the datePicker you can use your own date formatter to set the text of the label accordingly, you might also both the datePicker and the label inside a UIView and make it clip to bounds

Solution 2:

I have the same problem. Im using following hack:

let datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
datePicker.preferredDatePickerStyle = .compact

// Removes Labels
datePicker.subviews.forEach({ $0.subviews.forEach({ $0.removeFromSuperview() }) })

Then I simply add this date picker on top of a view, which should open this popup.

Solution 3:

It's impossible to open a UIDatePicker with UIKit14 from within the code

  • UIDatePicker has no API for doing this
  • UIKit doesn't allow us to create a UIEvents or UITouch object which has any impact on UIKit.

Solution 4:

Unfortunately it's not possible to programatically display the date selector popup, at least not resorting to hacks that might result in your app being rejected:

  • the UIDatePicker control doesn't expose any events that can be programatically triggered via sendActions(for:) - allControlEvents returns an empty option set

  • programatically simulating a user click is officially impossible on iOS - there is no public API to achieve this, all workarounds imply resorting to private API's

  • if the above wouldn't be enough, the UI structure of UIDatePicker is composed of private classes:

    enter image description here enter image description here

The conclusion is that in its current state, the UIDatePicker UI can be controlled only via user interactions. Maybe this will change in the future, for example UIButton's expose actions for triggering the same behaviour as when the user tapped the button, so maybe UIDatePicker will expose such actions in the future.