create a grid where the squares can be moved with matched geometry effect in swiftui in swift

To create a grid where the squares can be moved with matched geometry effect, you can use the following code in SwiftUI:

main.swift
struct SquareView: View {
    @Namespace var animation
    @State var isExpanded = false
    
    var body: some View {
        VStack {
            if !isExpanded {
                Rectangle()
                    .fill(Color.blue)
                    .frame(width: 100, height: 100)
                    .matchedGeometryEffect(id: "blueSquare", in: animation)
                    .onTapGesture {
                        withAnimation {
                            isExpanded.toggle()
                        }
                    }
            } else {
                VStack {
                    Rectangle()
                        .fill(Color.blue)
                        .frame(width: 300, height: 300)
                        .matchedGeometryEffect(id: "blueSquare", in: animation)
                        .onTapGesture {
                            withAnimation {
                                isExpanded.toggle()
                            }
                        }
                }
            }
        }
    }
}

struct GridView: View {
    var body: some View {
        let columns: [GridItem] = Array(repeating: .init(.flexible()), count: 3)
        LazyVGrid(columns: columns, spacing: 15) {
            ForEach(0..<9) { index in
                SquareView()
            }
        }
    }
}
1312 chars
44 lines

In this code, we have a SquareView with a Rectangle that has a blue fill. We use .matchedGeometryEffect to match the id of the blue square in the SquareView with the GridView. We have an @State variable isExpanded that toggles when the square is tapped. When the square is not expanded, it has a width and height of 100. When the square is expanded, it has a width and height of 300.

In the GridView, we have a LazyVGrid with three columns and a spacing of 15. We use a ForEach loop to create nine SquareView.

gistlibby LogSnag