ios – SwiftUI: The way to correctly enable person to vary dragged ingredient’s color afer drag gesture


I’m making an attempt to create app that permits person to pull by the grid, and alter color of every touched cell. Some sort of pixel artwork drawing machine, however after making easy instance it does not work, and I do not know why.

Right here is my code:

struct Cell: View, Hashable, Equatable {
    @State var colour: Shade = .purple
    let id = UUID()
    
    static func == (lhs: Cell, rhs: Cell) -> Bool {
        return lhs.colour == rhs.colour
    }

    func hash(into hasher: inout Hasher) {
        hasher.mix(colour)
    }

    var physique: some View {
        Rectangle()
            .body(width: 40, top: 40)
            .foregroundColor(colour)
    }
}

struct Grid: View {
    
    @State personal var cells: [[Cell]] = (0..<10).map { _ in
        (0..<10).map { _ in Cell() }
    }

    var physique: some View {
        VStack(spacing: 0) {
            ForEach(cells, id: .self) { row in
                HStack(spacing: 0) {
                    ForEach(row, id: .id) { cell in
                        cell
                    }
                }
            }
        }
        .background(Shade.black)
        .gesture(
            DragGesture()
                .onChanged { worth in
                    let width = 40
                    let top = 40
                    let x = Int(worth.location.x / CGFloat(width))
                    let y = Int(worth.location.y / CGFloat(top))
                    // Be sure the indices are inside the bounds of the grid
                    if x >= 0 && x < 10 && y >= 0 && y < 10 {
                        self.cells[y][x].colour = .inexperienced
                    }
                }
        )
    }
}

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles