簡體   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