skip to Main Content

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 it doesn’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)
        }

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search