Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DatePicker on Mac not saving date until return key is pressed

I'm adapting my iPad app to Mac with Mac Catalyst and am having a problem with the datePicker (it has a datePickerMode of time). On iPad the datePicker is a wheel and whenever the user scrolls on the date picker the dateChanged action is fired. But on Mac the date picker is not a scroller and is instead a type of text input. I can type and change all the time values on Mac, but the dateChanged action won't be fired until I press the return key.

I would like to get the dateChange action fired whenever a user is entering in a time. How can I do this? I tried adding different targets to the datePicker but nothing work.

I actually prefer to have the date scroller on the Mac so if anyone knows how to do this instead I would greatly appreciate it (I looked all over the internet for this and found nothing)!

Here's my code:

class DateVC: UIViewController {
     @IBOutlet weak var datePicker: UIDatePicker!

     override func viewDidLoad() {
          super.viewDidLoad()

          //Just show the time
          datePicker.datePickerMode = .time
    }

     //Action connected to datePicker. This is not called until I press enter on Mac
     @IBAction func datePickerChanged(_ sender: Any) {
        //do actions
     }

}
like image 830
fphelp Avatar asked Apr 26 '20 22:04

fphelp


2 Answers

I have filed a bug report with Apple about 1 week ago. For now I a doing the following to force the datepicker to use the wheel format. This fires the onchangedlistener as the wheels are spun.

if #available(macCatalyst 13.4, *) {
    datePickerView.preferredDatePickerStyle = .wheels
}
like image 88
gbotha Avatar answered Nov 04 '22 03:11

gbotha


Because your function linked with @IBAction which is to be called upon action, like 'button press'

you should follow different approach.

let datePicker = UIDatePicker()
    datePicker.datePickerMode = .date
    dateTextField.inputView = datePicker



datePicker.addTarget(self, action: #selector(datePickerChanged(picker:)), for: .valueChanged)

and here is your function:

@objc func datePickerChanged(picker: UIDatePicker) {
    //do your action here
}
like image 43
Osman Tüfekçi Avatar answered Nov 04 '22 03:11

Osman Tüfekçi