I have view struct created with code below:
struct ElementsView: View {
@State private var selectedElement: String = "First element"
let data: [String] = [
"First element",
"Second Longer Element",
"3 element",
"Forth Element",
"Fifth Longer element",
"6 Element"
]
let columns: [GridItem] = [
GridItem(.adaptive(minimum: 100, maximum: 120), alignment: .leading)
]
var body: some View {
LazyVGrid(columns: columns, alignment: .leading, spacing: 8) {
ForEach(data, id: .self) { element in
Button {
selectedElement = element
} label: {
Text(element)
.font(.system(size: 16))
.multilineTextAlignment(.leading)
.padding(10)
.background {
if selectedElement == element {
Capsule()
.foregroundColor(.blue)
.background {
Capsule()
.stroke(lineWidth: 2)
.foregroundColor(.black)
}
} else {
Capsule()
.foregroundColor(.white)
}
}
}
.buttonStyle(PlainButtonStyle())
}
}
.padding()
}
}
It looks like this:
I want it to look like this:
There should be minimal spaces between each element in row and each row should have as many elements as it can so that the elements labels would be in one line.
Is it achievable using Grids system or should I use many HStacks?
1