ufookoro
ufookoro

Reputation: 373

Xcode SwiftUI Button - Unable to Centre

I am new to SwiftUI and I would some assistance with regards positioning of a Custom Button which I am unable to to centre. I have used VStack and HStack to try and get the button bottom centered, but button keeps aligning left. Any assistance will be appreciated.

struct ContentView: View {
    var body: some View {

        VStack {
            NavigationView {

                Section {
                VStack(alignment: .leading) {


                    Text("Meal Description").foregroundColor(.green)
                    Spacer()

                            NavigationLink(destination: PoundedYam()) {
                                Text("Pounded Yam & Egusi Soup")
                    }

                            NavigationLink(destination: YamPepSoup()) {
                                Text("Yam and Pepper Soup")
                            }


                        NavigationLink(destination: JollofRice()) {
                                Text("Jollof Rice & Plantain")
                        }

                    Spacer()
                        .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .topLeading)



                    }.padding()

                }


                Section {

                    Image("africanfoods")
                        .resizable()
                        .frame(width: 275.0, height: 250.0)
                        .clipShape(Circle())
                        .overlay(Circle().stroke(Color.black, lineWidth: 5))
                        .scaledToFit()

                }


                    VStack { //For Button
                        Spacer()

                            Button( action: {},
                            label: { Text("Create Order") })

                    }                    
                    .navigationBarTitle(Text("Menu"))


                } //NavView End


        } //VStack End

    }

}

Upvotes: 2

Views: 3694

Answers (3)

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 119128

You can add .frame(maxWidth: .infinity) to the Button. This will also increase teachability.

Button("Create Order") { }
.frame(maxWidth: .infinity)

Upvotes: 7

Chris
Chris

Reputation: 8091

May be not most elegant solution but it works:

HStack() {
     Spacer()
     Button( action: {},
       label: { Text("Create Order") })
     Spacer()
}

Upvotes: 5

Hrabovskyi Oleksandr
Hrabovskyi Oleksandr

Reputation: 3265

First fast idea: set your button in HStack between Spacers:

// ...
VStack { //For Button
    Spacer()

    HStack {
        Spacer()
        Button( action: {}, label: { Text("Create Order") })
        Spacer()
        }    
}
.navigationBarTitle(Text("Menu"))
// ...

and the result is:

enter image description here

Upvotes: 0

Related Questions