您可以使用一系列嵌套的
HStack
和 VStack
。通过 aspectRatio(1, contentMode: .fit)
将视图变成正方形。
struct ContentView: View {
var body: some View {
VStack {
HStack {
ForEach(0..<4) { _ in Square() }
}
HStack {
VStack {
Square()
Square()
}
Square()
VStack {
Square()
Square()
}
}
HStack {
ForEach(0..<4) { _ in Square() }
}
}
.aspectRatio(1, contentMode: .fit)
.padding()
}
}
struct Square: View {
var body: some View {
Rectangle().stroke()
.aspectRatio(1, contentMode: .fit)
}
}
输出:
在您的屏幕截图中,正方形的垂直间距似乎比水平间距更大。这可以通过向
(spacing: ...)
和 VStack
添加不同的 HStack
参数来实现。