Reputation: 5136
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:
in button's HStack, the buttons should spread evenly over the entire container.
in containing VStack, the division should be that the label take 10% of the whole view, button's HStack will consume additional 30% and the text will take the rest (another 60%)
when the main view is opened, the size will be 500x300.
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.
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
Reputation: 258117
You need all buttons be like this
Button(action: {
self.buttonText = "bbb"
}, label : {
Text("B")
.frame(maxWidth: .infinity) // << !!
})
Upvotes: 6