Reputation: 447
I want to make a lazyvgrid with multiple columns as bellow. Large size items can be aligned with two smaller sizes.
My code is as bellow:
struct ContentView: View {
let paddingLeft: CGFloat = 22.0
var body: some View {
let widgetWidth: CGFloat = 72.0
let widgetHeight: CGFloat = widgetWidth
let col: Int = 4
let widgetGap: CGFloat = floor((UIScreen.main.bounds.size.width - paddingLeft * 2 - widgetWidth * CGFloat(col)) / CGFloat(col - 1))
let widgetWidthx2: CGFloat = widgetWidth * 2 + widgetGap
let colums1 = [GridItem(.adaptive(minimum: widgetWidth), spacing: widgetGap)]
LazyVGrid(columns: colums1, spacing: widgetGap){
ForEach(0 ..< 11){ idx in
RoundedRectangle(cornerRadius: 5)
.foregroundColor(Color(hue: 0.1 * Double(idx) , saturation: 1, brightness: 1))
.frame(width: idx == 4 ? widgetWidthx2 : widgetWidth, height: widgetHeight)
}
}
.padding(.horizontal, paddingLeft)
}
}
However, the result was not as expected:
Is there any way to make swiftui lazyvgrid multiple columns?
Upvotes: 1
Views: 1771
Reputation: 447
I find a solution:
struct ContentView: View {
let paddingLeft: CGFloat = 22.0
var body: some View {
let widgetWidth: CGFloat = 72.0
let widgetHeight: CGFloat = widgetWidth
let col: Int = 4
let widgetGap: CGFloat = floor((UIScreen.main.bounds.size.width - paddingLeft * 2 - widgetWidth * CGFloat(col)) / CGFloat(col - 1))
let widgetWidthx2: CGFloat = widgetWidth * 2 + widgetGap
let colums1 = [GridItem(.adaptive(minimum: widgetWidth), spacing: widgetGap, alignment: .leading)] //-- here alignment: .leading
LazyVGrid(columns: colums1, spacing: widgetGap){
ForEach(0 ..< 11){ idx in
RoundedRectangle(cornerRadius: 5)
.foregroundColor(Color(hue: 0.1 * Double(idx) , saturation: 1, brightness: 1))
.frame(width: idx == 4 ? widgetWidthx2 : widgetWidth, height: widgetHeight)
if idx == 4 {
Color.clear
}
}
}
.padding(.horizontal, paddingLeft)
}
}
Upvotes: 1