Why is there a sound if displaying a datePicker with Time Component

Viewed 49

If displaying the datePicker there is a strange behavior.

If pressing the button, then the time picker will appear, but while appearing the picker sound is noticeable. This is a little bit annoying. Why is this happening? If I remove the GraphicalDatePickerStyle then this disappears, but I want that the wheel can be dragged in the same place. I don't want a detail view popup which would be really annoying.

In result the time picker should go on top of a date picker which is showing the calendar, so I want to have a picker view which shows the date+time without having to go into a detail view. Thanks a lot for answers.

struct ContentView: View {
    @State var toggle = false
    @State var date = Date(timeIntervalSinceNow: 0)
    var body: some View {
        ZStack{
            Button("sdflkj"){
                toggle.toggle()
            }
            VStack{
                Spacer()
                if toggle{
                    DatePicker("lsadjf", selection: $date, displayedComponents: .hourAndMinute)
                        .labelsHidden()
                        .datePickerStyle(GraphicalDatePickerStyle())
                }
            }
        }
   
    }
}
1 Answers

This is standard behavior of the picker. If you don't want the click when it appears, but want it hidden when not in use, you can always do this:

        VStack {
            Spacer()
            DatePicker("lsadjf", selection: $date, displayedComponents: .hourAndMinute)
                .labelsHidden()
                .datePickerStyle(GraphicalDatePickerStyle())
                .opacity((toggle ? 1 : 0))
        }

This makes the view invisible until toggled. Another common way is a bit more complex, but not by much.

Add a View extension:

extension View {
    @ViewBuilder func isHidden(_ hidden: Bool) -> some View {
        if hidden {
                self.hidden()
        } else {
            self
        }
    }
}

Then use it like this:

        VStack{
            Spacer()
            DatePicker("lsadjf", selection: $date, displayedComponents: .hourAndMinute)
                .labelsHidden()
                .datePickerStyle(GraphicalDatePickerStyle())
                .isHidden(toggle)
        }

Either way prevents the "click" sound when the DatePicker appears.

Related