SwiftUI - 拖放圆圈

问题描述

我正在尝试创建可以拖放的圆圈。

我只能在第一个圆圈中使用它,但是,第一个圆圈之后的任何东西都不起作用。

预期行为:拖动时圆圈跟随我的光标,拖动结束时落在最终位置

实际行为:圆圈跟随我光标的水平位置,而不是垂直位置(垂直位置总是明显低于我的光标)

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)
        }
        
    }


解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)