What I am trying to achieve
Making this grid layout using Stack in SwiftUI
How I've currently achieved (with Xcode 14.0.1 (14A400))
import SwiftUI
struct ForStackOverflow: View {
let spacerSize: CGFloat = 1
var body: some View {
VStack(spacing: spacerSize) {
HStack(spacing: spacerSize) {
makeComponent(text: "A")
makeComponent(text: "B")
makeComponent(text: "C")
makeComponent(text: "D")
}
HStack(spacing: spacerSize) {
VStack(spacing: spacerSize) {
HStack(spacing: spacerSize) {
makeComponent(text: "E")
makeComponent(text: "F")
makeComponent(text: "G")
}
HStack(spacing: spacerSize) {
makeComponent(text: "H")
makeComponent(text: "I")
makeComponent(text: "J")
}
HStack(spacing: spacerSize) {
makeComponent(text: "K")
}
}
makeComponent(text: "L")
// 1. Is there any better way to make the width of L the same width of D?
.frame(width: (UIScreen.main.bounds.width - 3) / 4 )
}
}
}
func makeComponent(text: String) -> some View {
// 2. Is there any better way to make the height of L the same height of (G + J + K)?
let height: CGFloat = text == "L" ? ((80 * 3) + (spacerSize * 2)) : 80
return Text(text)
.frame(minWidth: 0, maxWidth: .infinity)
.frame(height: height)
.background(Color.red)
.foregroundColor(.white)
}
}
struct ForStackOverflow_Previews: PreviewProvider {
static var previews: some View {
ForStackOverflow()
}
}
Questions
1. Is there any better way to make the width of L the same width of D?
Layout would not look ok without the code below
let height: CGFloat = text == "L" ? ((80 * 3) + (spacerSize * 2)) : 80
2. Is there any better way to make the height of L the same height of (G + J + K)?
I do not desperately want to solve this one, but if you guys have any suggestion, please let me know.