SwiftUI - 拖放圆形

3
我正在尝试创建可拖放的圆形。
我可以让第一个圆形正常工作,但是在第一个之后的圆形无法正常工作。
期望行为:当拖动时,圆形跟随光标移动,并在拖动结束时停留在最终位置。
实际行为:圆形跟随光标的水平位置移动,但垂直位置始终明显低于光标。

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack(alignment: .center) {
            ForEach(0..<5) { _ in
                DraggableCircles()
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct DraggableCircles: View {
    @State var dragAmount: CGPoint = CGPoint.zero

        var body: some View {
            Circle().fill(Color.red)
            .frame(width: 50, height: 50)
                .gesture(
                    DragGesture(coordinateSpace: .global).onChanged {action in
                        let location = action.location
                        let newWidth = location.x
                        let newHeight = location.y
                        let size = CGPoint(x: newWidth, y: newHeight)
                        self.dragAmount = size
                    }.onEnded{action in
                        let location = action.location
                        let newWidth = location.x
                        let newHeight = location.y
                        let size = CGPoint(x: newWidth, y: newHeight)
                        self.dragAmount = size
                    }
                )
                .position(x: dragAmount.x, y: dragAmount.y)
        }
        
    }


1个回答

7

你需要将拖曳值添加到最后一个位置。正确的计算如下。

struct DraggableCircles: View {
    
    @State private var location: CGPoint = CGPoint(x: 50, y: 50)
    @GestureState private var startLocation: CGPoint? = nil
    
    var body: some View {
        
        // Here is create DragGesture and handel jump when you again start the dragging/
        let dragGesture = DragGesture()
            .onChanged { value in
                var newLocation = startLocation ?? location
                newLocation.x += value.translation.width
                newLocation.y += value.translation.height
                self.location = newLocation
            }.updating($startLocation) { (value, startLocation, transaction) in
                startLocation = startLocation ?? location
            }
        
        return Circle().fill(Color.red)
            .frame(width: 50, height: 50)
            .position(location)
            .gesture(dragGesture)
    }
}

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接