Home > Enterprise >  how to Select current time without scrolling picker view
how to Select current time without scrolling picker view

Time:11-16

I am not able to select current time without scrolling picker view .

I am doing this -:

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

this is for open picker view -:

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

CodePudding user response:

I have attached the function that give you current time.

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
}

-> Call above function in ViewDidLoad() and pass current date from picker like below code.

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

-> For Selected date and time from date picker.

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