如何在不滚动选择器视图的情况下 Select 当前时间

how to Select current time without scrolling picker view

如果不滚动选择器视图,我无法select当前时间。

我正在做这个-:

@objc func dateChanged(_ sender: UIDatePicker?) {
        let dateFormatter = DateFormatter()
        dateFormatter.timeStyle = .short
        dateFormatter.dateFormat = "HH:mm"
        if let date = sender?.date {
            reminderLbl.text = dateFormatter.string(from: date)
           }
}

这是用于打开选择器视图 -:

 func openDatePickerView(){
    datePicker = UIDatePicker.init()
    datePicker.autoresizingMask = .flexibleWidth
    datePicker.datePickerMode = .time
    if #available(iOS 13.4, *) {
        datePicker.preferredDatePickerStyle = .wheels
        datePicker.backgroundColor = UIColor.white
    } else {
        // Fallback on earlier versions
    }
    datePicker.addTarget(self, action: #selector(self.dateChanged(_:)), for: .valueChanged)
    datePicker.frame = CGRect(x: 0.0, y: UIScreen.main.bounds.size.height - 300, width: UIScreen.main.bounds.size.width, height: 300)
    self.view.addSubview(datePicker)
    toolBar = UIToolbar(frame: CGRect(x: 0, y: UIScreen.main.bounds.size.height - 300, width: UIScreen.main.bounds.size.width, height: 50))
    toolBar.barStyle = .default
    toolBar.items = [UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.onDoneButtonClick))]
    toolBar.sizeToFit()
    self.view.addSubview(toolBar)
}

我附上了给你当前时间的功能。

func getTimeFrom(date: Date) {
    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = DateFormatter.Style.short
    dateFormatter.timeZone = TimeZone.current
    let time = dateFormatter.string(from: date)
    lbl_Time.text = time
}

-> 在 ViewDidLoad() 中调用上述函数,并像下面的代码一样从选择器传递当前日期。

override func viewDidLoad() {
    super.viewDidLoad()
    getTimeFrom(date: datePicker.date)
}

-> 对于从日期选择器中选择的日期和时间。

@IBAction func actionPicker(_ sender: UIDatePicker) {
    getTimeFrom(date: sender.date)
}