question10101
question10101

Reputation: 69

Centering DatePicker inside a section

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:

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)
        }

Upvotes: 1

Views: 437

Answers (2)

burnsi
burnsi

Reputation: 7754

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

Upvotes: 1

stosha
stosha

Reputation: 2148

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

Upvotes: 0

Related Questions