1

I have the following code that created a grid and populates it with characters from an array. I have added the gesture code but it enables drag on the entire grid and not on individual cells.

import SwiftUI

struct GridStack<Content: View>: View {
    let rows: Int
    let columns: Int
    let content: (Int, Int) -> Content
    @State private var currentPosition: CGSize = .zero
    @State private var oldPosition: CGSize = .zero
    @State private var newPosition: CGSize = .zero
    var body: some View {
        VStack {
            ForEach(0 ..< rows, id: \.self) { row in
                HStack(spacing: 0) {
                    ForEach(0 ..< self.columns, id: \.self) { column in
                        self.content(row, column).font(.custom("Rockwell",size:24)).frame(width: 30, height: 30).padding()
                    }.border(Color.gray)
                        .offset(x: self.currentPosition.width, y: self.currentPosition.height)
                    .gesture(DragGesture()
                        .onChanged { value in
                            self.currentPosition = CGSize(width: value.translation.width + self.newPosition.width, height: value.translation.height + self.newPosition.height)
                        }   // 4.
                        .onEnded { value in
                            self.currentPosition = self.oldPosition
                            self.newPosition = self.oldPosition
                        }
                    )
                }
            }
        }
    }

    init(rows: Int, columns: Int, @ViewBuilder content: @escaping (Int, Int) -> Content) {
        self.rows = rows
        self.columns = columns
        self.content = content
    }
}

How can I enable drag on each individual cell?

Jill Evans
  • 11
  • 1

0 Answers0