9

I'm showing a SwiftUI DatePicker with the datePickerStyle of type WheelDatePickerStyle(). It's inside a Section, which is within a Form. As I'm showing a Section Header, I don't want to show the Picker's label. When choosing .labelsHidden(), however, the Picker just moves to the left and leaves some space to the left.

How can I either center the picker, or make sure that it takes up the full width of the Section / Form?

DatePicker("Please enter a time", selection: $time, displayedComponents: .hourAndMinute)
    .labelsHidden()
    .datePickerStyle(WheelDatePickerStyle())
Gerjan
  • 93
  • 2
  • 5

2 Answers2

11
DatePicker("Please enter a time", selection: $time, displayedComponents: .hourAndMinute)
    .labelsHidden()
    .datePickerStyle(WheelDatePickerStyle())
    .frame(minWidth: 0, maxWidth: .infinity, alignment: .center)
Rudrank Riyam
  • 588
  • 5
  • 13
1

You don't need the label. Just like the following:

   DatePicker("", selection: $time, displayedComponents: .hourAndMinute)
    // .labelsHidden()
    .datePickerStyle(WheelDatePickerStyle())

Another simple way is to use HStack with Spacer() at both sides.

HStack{
    Spacer()
    DatePicker.init(selection: $time, displayedComponents: .hourAndMinute, label: {
        EmptyView()
        })
        .labelsHidden().datePickerStyle(WheelDatePickerStyle())
    Spacer()
    }
E.Coms
  • 11,065
  • 2
  • 23
  • 35
  • 1
    I like the second suggestion! The label is also used for screen readers, so an empty String isn't an ideal option. – Gerjan Nov 04 '19 at 08:24