简体   繁体   中英

iOS Swift - Set Start Time and End Time (Fututre Time only) UIDatePicker

I want to make an employee attendance app. I have two time pickers, I use the UIDatePickerMode.time. The first time picker is for the user to select the Starting Time and the second time picker is for the Finishing Time,

example: Starting Time: 8:00 AM, Finishing Time: 5:00PM.

How do I set the second time picker to only allow selection of time from 8:01 AM onwards? So the user will not be able to select earlier time but future time only,

example: Starting Time: 8:00 AM, Finishing Time: 7:00 AM. How do I avoid this?

Please help. Thank you.

You could update data for second picker in UIPickerViewDelegate method right after selecting row in first picker:

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if pickerView == startPicker {
        // update endPicker.minimumDate
        endPicker.minimumDate = Calendar.current.date(byAdding: .minute, value: 1, to: pickerView.date)
        // don't forget to add some checks (for example if your startPicker time is set to 23:59)
    }
}

Updated:

For UIDatePicker (not UIPickerView ):

startPicker.addTarget(self, action: #selector(datePickerValueChanged(_:)), for: .valueChanged)

And in method do something like that

func datePickerValueChanged(_ datePicker: UIDatePicker) {
    endPicker.minimumDate = Calendar.current.date(byAdding: .minute, value: 1, to: datePicker.date)
    // don't forget to add some checks (for example if your startPicker time is set to 23:59)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM