NSDatePicker focus on day of the month editing

妖精的绣舞 提交于 2020-05-24 05:18:17

问题


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?


回答1:


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)!)!)
            }
        }
    }

}



来源:https://stackoverflow.com/questions/61721346/nsdatepicker-focus-on-day-of-the-month-editing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!