3

I hope my title is self explanatory enough. I have an hours and minutes time picker, where every minute is shown individually. What I want is to only show the "00" and "30" minutes. Is this achievable?

The code I use for the time picker:

DatePicker("", selection: $selectedStartHour, displayedComponents: .hourAndMinute)
    .datePickerStyle(CompactDatePickerStyle())
    .labelsHidden()
    .clipped()

enter image description here

lex
  • 113
  • 8

1 Answers1

6

The comment posted is wrong. You can of course do this with a one line piece of code:

UIDatePicker.appearance().minuteInterval = 30

The issue is that now all of your time pickers throughout your entire app will be in 30 minute increments. To alleviate this, you use .onAppear and .onDisappear as follows:

.onAppear {
    UIDatePicker.appearance().minuteInterval = 30
}

.onDisappear {
    UIDatePicker.appearance().minuteInterval = 1
}

Now, when your view appears the picker will be set to 30 minute increments. When the view disappears, it will be set back to the default of 1 minute increments.

Now you can easily control what time increment is displayed on a per view basis.

kittonian
  • 1,020
  • 10
  • 22
  • 1
    Late reply, but thank you so much! There came a time where I needed a 30 min time interval again, and I saw your answer. Thank you, it works perfectly! – lex Dec 20 '22 at 06:36
  • How would I apply "60 minute" intervals just showing 00 for the minute "field"? – Alhomaidhi Mar 29 '23 at 20:23
  • From the code: "interval must be evenly divided into 60. default is 1. min is 1, max is 30" – Niklaus Aug 20 '23 at 15:12