🦋

SwiftUI: なぞったセルに色をつける

2022/08/26に公開


デモ

DragGestureを使ってなぞりながら当たり判定をします。GeometryReaderは不要です。

struct ContentView: View {
    private let r: CGFloat = 30
    private let g: CGFloat = 1
    @State var currentLocation: (x: Int, y: Int) = (-1, -1)
    @State var cells: [Bool] = Array(repeating: false, count: 10 * 10)

    var body: some View {
        VStack(spacing: g) {
            ForEach(0 ..< 10) { y in
                HStack(spacing: g) {
                    ForEach(0 ..< 10) { x in
                        Rectangle()
                            .frame(width: r, height: r)
                            .foregroundColor(cells[10 * y + x] ? Color.primary : Color.secondary)
                    }
                }
            }
        }
        .gesture(
            DragGesture(minimumDistance: 0)
                .onChanged({ value in
                    let x = Int(value.location.x / (r + g))
                    let y = Int(value.location.y / (r + g))
                    if (0 ..< 10).contains(x), (0 ..< 10).contains(y) {
                        if currentLocation.x != x || currentLocation.y != y {
                            currentLocation = (x, y)
                            cells[10 * y + x] = true
                        }
                    }
                })
                .onEnded({ value in
                    cells = Array(repeating: false, count: 10 * 10)
                    currentLocation = (-1, -1)
                })
        )
        .padding()
    }
}

Discussion