Search code examples
formsswiftuidatepicker

Center DatePicker Vertically within Form SwiftUI


Is there any way to center this datepicker vertically? This is clearly possible if we ditch the Form (and use VStack and Spacers), but as a constraint, try to keep the form. Or if you need to get rid of the form, I would prefer a way to keep the identical gray background color that the form generates. I happen to like the exact shade of gray that the form generates as a background.

Sample Code:

struct TestDate: View {
    @State var chosenDate = Date()

    var body: some View {
        Form {
            DatePicker("Date", selection: $chosenDate, in: Date()..., displayedComponents: [.hourAndMinute, .date])
            .datePickerStyle(GraphicalDatePickerStyle())
        }
    }
}

EDIT:

I have tried putting spacers around the Form and putting spacers within the Form (both within VStacks). I also checked if Form has any parameters I can change on init, but unlike VStack and HStack, there does not appear to be any alignment or spacing parameters on Form. Only content:


Solution

  • you could try something like this instead:

    struct TestDate: View {
        @State var chosenDate = Date()
    
        var body: some View {
            ZStack {
                Color(red: 236/255, green: 236/255, blue: 236/255, opacity: 1).ignoresSafeArea(.all)
                VStack {
                    Spacer()
                    DatePicker("Date", selection: $chosenDate, in: Date()..., displayedComponents: [.hourAndMinute, .date])
                        .datePickerStyle(GraphicalDatePickerStyle())
                        .background(Color.white)
                        .cornerRadius(15)
                        .padding(10)
                    Spacer()
                }
            }
        }
    }