3

I want to make a lazyvgrid with multiple columns as bellow. Large size items can be aligned with two smaller sizes.

enter image description here

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:

enter image description here

Is there any way to make swiftui lazyvgrid multiple columns?

0

1 Answer 1

1

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)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.