繁体   English   中英

SwiftUI - 拖放圆圈

[英]SwiftUI - Drag and drop circles

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

我可以让它与第一个圆圈一起工作,但是,第一个圆圈之后的任何东西都不起作用。

预期行为:当拖动结束时,圆圈跟随我的 cursor 并降落在最终 position 上

实际行为:圆跟随我光标的水平 position,但不是垂直 position(垂直 position 总是显着低于我的光标)

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


您必须将拖动值添加到最后一个位置。 正确的计算在这里。

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

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM