Home > Software engineering >  i want to put restrictions on my time pickers
i want to put restrictions on my time pickers

Time:02-15

I'm making time pickers using textfields. for example if current time is 8:00 i want the start time to be from 8:00 to 8:30 ONLY include every minute like 8:01 8:02 etc. And not allowing user to choose time from past like 7:00. for the end time if the current time is 8:00 i want it to start from 8:30 (the end of the start time) to the end of the day and as well as the start time it shouldn’t allow user to reserve past time. I know it little bit confusing but can anybody help me how to set these restrictions. Attached my code.

            
            StartTimeTxt.textAlignment = .center
            EndTimeTxt.textAlignment = .center
            
            //tool bar
            let toolbar = UIToolbar()
            toolbar.sizeToFit()
            
            //bar button(
           let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressed))
           toolbar.setItems([doneBtn], animated: true)
        
            //assign tool bar
            StartTimeTxt.inputAccessoryView = toolbar
            EndTimeTxt.inputAccessoryView = toolbar
            
            // assign time picker to the txt field
            StartTimeTxt.inputView = StartTimePicker
            EndTimeTxt.inputView = EndTimePicker
            
            //time picker mode
            StartTimePicker.datePickerMode = .time
            EndTimePicker.datePickerMode = .time
            
             if #available(iOS 13.4, *)  {
                   StartTimePicker.preferredDatePickerStyle = .wheels
                   EndTimePicker.preferredDatePickerStyle = .wheels
               }
        
        }```

CodePudding user response:

You need to set the range for each date picker so here is a way to calculate the two ranges

let calendar = Calendar.current
//First range
let startTime = Date()
let startRangeEnd = calendar.date(byAdding: DateComponents(minute: 30), to: startTime)!
let startRange = startTime...startRangeEnd
//Second range
let endTime = calendar.date(byAdding: DateComponents(minute: 1), to: startRangeEnd)!
let endRangeEnd = calendar.startOfDay(for: calendar.date(byAdding: DateComponents(day: 1), to: startTime)!)
set endRange = endTime...endRangeEnd

This was tested using DatePicker and SwiftUI but I assume it will work fine for UIKit as well.

Edit: I just checked the documentation for UIDatePicker and it doesn't use a range so the solution is a bit different between UIKit and SwiftUI. See below

For SwiftUI one would init the DatePicker with the range

DatePicker("Start Time", selection: $startTime, in: startRange, displayedComponents: [.hourAndMinute]) 

while for UIKit the min and max dates are set on an instance of UIDatePicker

startDatePicker.date = startTime
startDatePicker.minimumDate = startTime
startDatePicker.maximumDate = startRangeEnd
  • Related