Home > Mobile >  Centering DatePicker inside a section
Centering DatePicker inside a section

Time:08-31

enter image description here

Hello! I am trying to center the DatePicker inside the Section in SwiftUI. The screenshot shows the current display and desired display.

I've attempted the following and they don't seem to work: putting DatePicker in VStack with .alignment as centered, using .frame(alignment: .center) on the section, and attempting to place center decorators to the DatePicker itself. The first 2^ center the text within the section, but not the actual DatePicker object itself on the screen.

An explanation on how to do this, and what to know for future cases like these would be super helpful. Thank you!

        NavigationView {
        Form {
            Section {
                VStack(alignment: .center) {
                    
                DatePicker("Please enter a time", selection: $wakeUpTime, displayedComponents: .hourAndMinute)
                    .labelsHidden()
                }
            } header: {
                Text("When do you want to wake up?")
                    .font(.headline)
            }
            .frame(alignment: .center)
            

        .navigationTitle("BetterRest")
        .toolbar {
            Button("Calculate", action: calculateBedtime)
        }

CodePudding user response:

You can use a HStack with two Spacer to acomplish this output in SwiftUI.

NavigationView {
    Form {
        Section {
            HStack{ //Convert to HStack
                Spacer() //add this
                DatePicker("Please enter a time", selection: $wakeUpTime, displayedComponents: .hourAndMinute)
                    .labelsHidden()
                Spacer() // add this
            }
        } header: {
            Text("When do you want to wake up?")
                .font(.headline)
        }
        .frame(alignment: .center)
        .navigationTitle("BetterRest")
        .toolbar {
            Button("Calculate", action: calculateBedtime)
        }
    }
}

Output:

enter image description here

CodePudding user response:

Try following code:

  var body: some View {
    NavigationView {
        Form {
            Section {
                DatePicker("Please enter a time",
                           selection: $wakeUpTime,
                           displayedComponents: .hourAndMinute)
            } header: {
                Text("When do you want to wake up?")
                    .font(.headline)
            }
            .frame(alignment: .center)
            .navigationTitle("BetterRest")
            .toolbar {
                Button("Calculate") {
                    print("Calculate")
                }
            }
        }
    }
  }

enter image description here

  • Related