objective-cswiftmacosnsdatepicker

NSDatePicker focus on day of the month editing


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?


Solution

  • 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