0

I have a code similar to this:

let datePicker = NSDatePicker(....)
self.addSubview(datePicker)
self.window?.makeFirstResponder(datePicker)

When makeFirstResponder is called first element gets editing focus. For U.S region this picks day of the month, because date format is DD-MM-YYYY. For other regions when date format is YYYY-MM-DD, YYYY gets editing focus. How can I force NSDatePicker to start editing day of the month no matter what date format is?

Willeke
  • 14,578
  • 4
  • 19
  • 47
Gintaras
  • 214
  • 2
  • 8

1 Answers1

0

You can use DateFormatter method func dateFormat(fromTemplate tmplate: String, options opts: Int, locale: Locale?) -> String? to check the current locale dateFormat, check the location of the day and send the tab key 0, 1 or 2 times:

import Cocoa

class ViewController: NSViewController {

    @IBOutlet weak var datePicker: NSDatePicker!

    override func viewWillAppear() {
        super.viewWillAppear()
        datePicker.locale = .init(identifier: "en_US")
        datePicker.dateValue = Date()
        if view.window?.makeFirstResponder(datePicker) == true {
            selectDayElement(from: datePicker)
        }
    }

    func selectDayElement(from datePicker: NSDatePicker) {
        if let firstIndex = DateFormatter
            .dateFormat(fromTemplate: "yyyyMMdd",
                        options: 0,
                        locale: datePicker.locale)?
            .components(separatedBy: .punctuationCharacters)
            .firstIndex(of: "dd") {
            (0..<firstIndex).forEach { _ in
                datePicker.keyDown(with: NSEvent(cgEvent: CGEvent(keyboardEventSource: nil, virtualKey: 48, keyDown: true)!)!)
            }
        }
    }

}

enter image description here

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • 1
    Following code has a problem when not first NSDatePicker's element is already selected. The workaround is to recreate NSDatePicker's cell and to reassign old cell's attributes – Gintaras May 12 '20 at 14:48