SwiftUI在移动/动画视图/形状上拖放

时间:2020-08-28 12:57:16

标签: swiftui

我正在尝试在SwiftUI中实现拖放功能。看来当视图没有动画效果时,以下代码可以正常工作。但是,当我使用偏移量移动视图时,拖动位置和视图会出现一些问题,例如视图位置与触摸位置不同,视图形状与原始位置不同。

无偏移动画(动画= false)的拖动效果很好:

Dragging without offset animation

拖动偏移动画(动画= true):

Dragging with offset animation true

代码段:

import SwiftUI

struct ContentView: View {
    @ObservedObject var dropDelegate = CircleDropDelegate()
    @State var animate = false

    var body: some View {
        VStack(alignment: .leading) {
            Spacer()
        
            Circle()
                .fill(Color.green)
                .offset(x: animate ? 100 : 0)
                .animation(Animation.linear(duration: 5).repeatForever(autoreverses: true))
                .frame(width: 50, height: 50)
                .onDrag({
                    return NSItemProvider(object: "circle" as NSString)
                })
        
            Spacer()
        
            Rectangle()
                .fill(Color.green)
                .frame(height: 150)
                .onDrop(of: ["public.text"], delegate: dropDelegate)
        
            Spacer()
        }
        .onAppear {
            animate = true
        }
        .padding()
        .background(Color.init(white: 0.7))
    }
}

class CircleDropDelegate: ObservableObject, DropDelegate {
    @Published var isEntered: Bool = false
    func performDrop(info: DropInfo) -> Bool {
        print("perform drop on box \(info)")
        return true
    }

    func dropEntered(info: DropInfo) {
        print("circle entered the box")
        isEntered = true
    }

    func dropExited(info: DropInfo) {
        print("circle exited the box")
        isEntered = false
    }
}

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

是否可以解决此问题?

0 个答案:

没有答案