UIDatePicker Not working In Mac Catalyst (Xcode 11 Beta 5)

1.6k Views Asked by At

We are converting our iOS app to Mac Catalyst compatible using Swift in Xcode 11 beta 5.

We have facing issue that default DatePicker not shown in window.

I am trying this solution for mac and it will add date picker in view but I want another proper solution. Any other suggestion?

func datepickerWillLoad() {
    self.datePicker.datePickerMode = .date
    self.datePicker.maximumDate = Date()
    self.datePicker.backgroundColor = UIColor.Theme.lightBackground
    self.datePicker.setValue(UIColor.Theme.whiteColor, forKeyPath: "textColor")
    self.datePicker.addTarget(self, action: #selector(didChangedDatePickerValue), for: .valueChanged)
    
    //if user open picker and without change click on done
    self.dateOfBirthTextField.addTarget(self, action: #selector(didChangedDatePickerValue), for: .editingDidEnd)
    
    #if targetEnvironment(macCatalyst)
        datePicker.frame = CGRect(x: 0, y: self.view.frame.height - 200 , width: self.view.frame.width, height: 200)
        self.view.addSubview(datePicker)
    #else
        self.dateOfBirthTextField.inputView = datePicker
    #endif
}
2

There are 2 best solutions below

0
gbotha On

I found that if I set the datepicker text color with self.datePicker.setValue(UIColor.Theme.whiteColor, forKeyPath: "textColor") then this caused the app to crash when loading the view. Try removing that line of code and it should work with mac catalyst.

1
MosTwanTedT On

In my opinion, the cause of the problem is that the UIDatePicker has been redesigned to a compact controller instead of iOS typical wheel (probably since Mac Catalyst 13.4+). Therefore, the color scheme could no longer be applied to the not existing wheel with the setValue-function and causes an error.

So I tried to get the wheel mode back to my UIDatePicker. Therefore, I added the following line to my UIDatePicker, which solved the issue for me:

if #available(macCatalyst 13.4, *) {
    myDatePicker.preferredDatePickerStyle = .wheels
    myDatePicker.datePickerMode = .date
} else {
    // Fallback on earlier versions
}

For earlier versions I hadn't this problem before, so I am hopefully fine with the solution, but please comment if you are facing the problem also with earlier versions, so I can adapt my code! :-)

Note: I noticed that the datePickerMode is set to default mode after changing the preferredDatePickerStyle, so make sure that you force the datePickerMode afterwards!