0

I am creating an alarm app using SwiftUI that allows a user to enter in how many hours of sleep they want which then calculates when the wake up time is from when they set the alarm but at the moment i am using a date picker to display the time like this:

EDIT: This is my code

@State private var hoursOfSleep = Date()

var body: some View {
    HStack {
        Text("Hours of Sleep").foregroundColor(Color.ui.textGray)
        Spacer()
        DatePicker("", selection: $hoursOfSleep, displayedComponents: .hourAndMinute)
             .accentColor(Color.ui.textGray)
             .frame(height: 20)
             .labelsHidden()
    }//: HStack
}

enter image description here

but this represents the actual time rather than the amount of hours and minutes so this would wake the user up at half past 7 rather than 7 hours and 30 min after setting the alarm.

Is there a better way for me to store the hours and minutes other than using a datepicker?

Any help would be much appreciated thank you.

Gino Sesia
  • 383
  • 2
  • 4
  • 14
  • Could you clarify what you want? Do you want to the picker to show the time of the alarm or the sleep duration? Where do you want to store or display the actual Date of the alarm? – Abizern Jul 21 '21 at 14:19
  • yes i want to store the duration of the alarm so that i can use it to work out the wake up time. So i want the picker to show 07:30 which would indicate the user wants to sleep for 7 hours and 30 min – Gino Sesia Jul 21 '21 at 14:21
  • 1
    One option here is to use 2 normal pickers, one for hours and one for minutes. The one for minutes could be limited to only 15 or 30 minute intervals. Then use the values together with the current time and DateComponents to calculate the wake up time – Joakim Danielson Jul 21 '21 at 14:41
  • I will try that thank you for helping – Gino Sesia Jul 21 '21 at 14:44
  • You could try writing a multi-component picker https://stackoverflow.com/questions/56567539/multi-component-picker-uipickerview-in-swiftui – Abizern Jul 21 '21 at 14:52
  • 1
    An alternative is the Count Down Picker style. This requires to wrap `UIDatePicker` in `UIViewRepresentable` as described [here](https://stackoverflow.com/questions/58574463/how-can-i-set-countdowntimer-mode-in-datepicker-on-swiftui). The count down appearance is better anyway for this purpose. – vadian Jul 21 '21 at 16:48

0 Answers0