DragGesture SwiftUI Tinder

//
//  ContentView.swift
//  tinder
//
//  Created by Артур Мугинов on 28.03.2022.
//

import SwiftUI

struct ContentView: View {
    @State var arr = [0, 1, 2, 3, 4, 5]
    
    func generateRandomColor() -> UIColor {
        let redValue = CGFloat(drand48())
        let greenValue = CGFloat(drand48())
        let blueValue = CGFloat(drand48())
            
        let randomColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1.0)
            
        return randomColor
        }
    
    var body: some View {
        GeometryReader { proxy in
            ZStack {
                if arr.count == 0 {
                    Text("Placeholder")
                } else {
                    ForEach($arr, id: \.self) { index in
                        let color = generateRandomColor()
                        CardView(arr: $arr, element: index, color: color, proxy: proxy)
                    }
                }
            }
        }
    }
}
struct CardView: View {
    @GestureState var translation: CGSize = .zero
    @GestureState var degrees: Double = 0
    @Binding var arr : [Int]
    @Binding var element : Int
    var color : UIColor
    // 1
    let proxy: GeometryProxy
    
    func getIndex() -> Int {
        return arr.firstIndex { el in
            return el == element
        } ?? 0
    }
    
    var body: some View {
        // 3
        Rectangle()
            // 4
            .background(Color(uiColor: color))
            .cornerRadius(10)
            // 5
            .frame(
                maxWidth: proxy.size.width - 28,
                maxHeight: proxy.size.height * 0.8
            )
            // 6
            .offset(x: translation.width)
            .rotationEffect(.degrees(degrees))
            .gesture(
                DragGesture()
                    .updating($translation) { (value, state, _) in
                        // 3
                        
                        state = value.translation
                        state.width = state.width + (state.width > 0 ? 150 : -150)
                        state.height = state.height + (state.height > 0 ? 150 : -150)
                    }
                    .updating($degrees) { (value, state, _) in
                        // 3
                       state = value.translation.width > 0 ? 10 : -10
                    }
                    .onEnded({ val in
                        if val.translation.width > 0 {
                            print("right")
                        } else {
                            print("left")
                        }
                        arr.removeFirst()
                    })
            
            )
            .animation(.interactiveSpring())
    }
}

Ответы (0 шт):