0

I have two pickers for workoutStartTime and workoutEndTime that default to Date.now but currently the user can set the end time earlier than the start time. How do you prevent this?

@State private var workoutName: String = ""
@State private var workoutStartTime: Date = Date.now
@State private var workoutEndTime: Date = Date.now
    
@State private var showExercieSheet = false
    
var body: some View {
    VStack {
        List {
            Section(header: Text("Workout Details")) {
                
                TextField("Enter workout name",text: $workoutName)
                DatePicker("Start Time", selection: $workoutStartTime)
                DatePicker("End Time", selection: $workoutEndTime)                            
            }
        }
    }
}
5
  • Test the change of one date to adjust the second time if no more valid.
    – Ptit Xav
    Commented Jul 10 at 9:52
  • I applied your comment and it worked I posted the answer Commented Jul 10 at 11:27
  • I don't see an answer, did you really post it?
    – soundflix
    Commented Jul 12 at 13:08
  • I deleted it because stack overflow banned me from asking anymore questions so I will assume all of the questions I ever asked are useless to people Commented Jul 12 at 13:34
  • I posted what I wrote in my comment and you add previously posted
    – Ptit Xav
    Commented Jul 12 at 14:20

2 Answers 2

1

Test the change of one date to adjust the second time if no more valid.

VStack {
    ...
    }
    .onChange(of: workoutStartTime) {
        // if new start time if after end time then adjust end time
        if workoutStartTime > workoutEndTime { 
            workoutEndTime = workoutStartTime
        }
    }
    .onChange(of: workoutEndTime) {
        // if new end time is before start time then adjust start time
        if workoutEndTime < workoutStartTime  {
            workoutStartTime = workoutEndTime
        }
    }
1

The Solution is to add onChanged modifiers to both DatePickers than if the endTime comes before the startTime make startTime equal that and vice versa:

            DatePicker("Start Time", selection: $workoutStartTime)
                .onChange(of: workoutStartTime) {
                    if(workoutStartTime > workoutEndTime) {
                        workoutEndTime = workoutStartTime
                    }
                 
                }
            
            DatePicker(
                "End Time",selection: $workoutEndTime)
            .onChange(of: workoutEndTime) { //not allowing endTime to be lower than StartTime
                if(workoutEndTime < workoutStartTime) {
                    workoutStartTime = workoutEndTime
                }
             
            }

Not the answer you're looking for? Browse other questions tagged or ask your own question.