Zohar81
Zohar81

Reputation: 5136

SwiftUI make buttons in HStack spread evenly over the entire container area

I wanted to create a view, that include VStack composed of a label, HStack of buttons and a text object on bottom.

My design principles are:

So here's my attempt :

struct ContentView: View {
  @State var buttonText: String = ""
  var body: some View {
    GeometryReader { metrics in
      VStack (alignment: .leading) {
        Label("my swiftui demo", systemImage: "gearshape")
          .frame(width: 400, height: metrics.size.height * 0.1, alignment: .center)
        HStack(alignment: .center, spacing: 10) {
          Button("A") {
            self.buttonText = "aaa\nbbb\nccc"
          }
          Button("B") {
            self.buttonText = "bbb"
          }
          Button("C") {
            self.buttonText = "aaa"
          }
          Button("D") {
            self.buttonText = "bbb"
          }
        }
        .frame(width: 400, height: metrics.size.height * 0.30)
        .border(Color.black)
        Text(buttonText)
          .frame(width:400, height: metrics.size.height * 0.50)
          .background(Color.white)
          .border(Color.black)
      }
      .frame(width: 500, height: 300, alignment: .center)
    }
  }
}

and here's the result I got.

enter image description here

It can be seen that the containing view's width takes much more than the selected 500 (basically I wanted that the Vstack components will be horizontally centralized and the margins will be 50 from each side.)

In addition, the buttons are not evenly spread over the button's HStack. I'd sick to find a way that the buttons will take most of the area in the containing view, and that their size will be change ac, leaving minor margin between each button and between the buttons and the view borders.

Perhaps anybody can instruct me how to fix it ? further comments are also appreciated :-)

Upvotes: 1

Views: 4611

Answers (1)

Asperi
Asperi

Reputation: 258117

You need all buttons be like this

    Button(action: {
        self.buttonText = "bbb"
    }, label : {
        Text("B")
            .frame(maxWidth: .infinity)    // << !!
    })

demo

Upvotes: 6

Related Questions