skip to Main Content

I have an almost working datepicker with the following settings:

  1. Preferred Style: Automatic
  2. Mode: Date
  3. Locale: Default
  4. 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


  1. Chosen as BEST ANSWER

    Okay, so something about animating the containerView from the bottom up was screwing with the display.

    Removing viewDidLayoutSubviews and capturing .setDate under a DispatchQueue.main.asyncAfter in viewWillAppear made things finally display correctly for me.


  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search