I have an almost working datepicker with the following settings:
- Preferred Style: Automatic
- Mode: Date
- Locale: Default
- Date: Current Date
My problem is the current month and year name do not appear on load. Instead, the right arrow icon is in its place, and the month and year name only show after I’ve selected a day from the calendar.
I’ve tried .setDate
on the datePicker in viewDidLayoutSubviews()
as a try, but still seeing the same result. Any guidance would be appreciated as I could not find any existing solution online.
I created the datePicker through storyboard, but here is the remaining code as it pertains to the datePicker onLoad:
override func viewDidLoad() {
super.viewDidLoad()
calendarDatePicker.preferredDatePickerStyle = .inline
calendarDatePicker.overrideUserInterfaceStyle = .dark
calendarDatePicker.date = //current date
calendarDatePickerContainerView.layer.cornerRadius = 8
calendarDatePickerContainerView.layer.masksToBounds = true
calendarDatePickerContainerViewBottomConstraint.constant -= self.view.bounds.size.height
self.view.layoutIfNeeded()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
guard let current = currentDate else { return }
calendarDatePicker.setDate(current, animated: true)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
DispatchQueue.main.async {
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: .curveEaseIn, animations: {
self.calendarDatePickerContainerViewBottomConstraint.constant = 0
self.view.layoutIfNeeded()
}, completion: nil)
}
}
2
Answers
Okay, so something about animating the containerView from the bottom up was screwing with the display.
Removing
viewDidLayoutSubviews
and capturing.setDate
under aDispatchQueue.main.asyncAfter
inviewWillAppear
made things finally display correctly for me.the reason is that your device is in dark mode.
in night mode, default label color is white.
so if UI background is white, it looks like the labels-month/year/day is hidden.
you can see the UIDatePicker label color or you can change the dark to light mode.