Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center button inside VStack Swift UI

Tags:

swift

swiftui

var body: some View {
    VStack(alignment: .leading) {
        Text("Title")
            .bold()
            .font(Font.custom("Helvetica Neue", size: 36.0))

        ...

        Button(action: {}){
            Text("Create")
            .bold()
            .font(Font.custom("Helvetica Neue", size: 24.0))
            .padding(20)
            .foregroundColor(Color.white)
            .background(Color.purple)
            .cornerRadius(12)
        }


    }.padding(20)
}

I want different alignments for these two particular elements. Title must have a leading alignment, but on the other hand button is located in the center. Now I set VStack alignment to leading. I'm not familiar with the Swift UI quite well, so the first idea is to use several vertical stacks with different alignments, but I assume it can be done easier. If I add alignment guide to the button, it doesn't work either.

like image 506
Joseph Kirtman Avatar asked Jan 09 '20 00:01

Joseph Kirtman


1 Answers

I would use included HStack as in demo below

enter image description here

var body: some View {
    VStack(alignment: .leading) {
        Text("Title")
            .bold()
            .font(Font.custom("Helvetica Neue", size: 36.0))

        HStack {
            Spacer()
            Button(action: {}){
                Text("Create")
                .bold()
                .font(Font.custom("Helvetica Neue", size: 24.0))
                .padding(20)
                .foregroundColor(Color.white)
                .background(Color.purple)
                .cornerRadius(12)
            }
            Spacer()
        }
    }.padding(20)
}
like image 188
Asperi Avatar answered Nov 07 '22 00:11

Asperi