简体   繁体   English

如何在 SwiftUI 上最后更新的 position 上启动手势?

[英]How to start the gesture on the last updated position on SwiftUI?

I'm having an issue that I can't figure out.我有一个我无法弄清楚的问题。 I can't seem to figure out how to start the gesture where my last gesture position ended.我似乎不知道如何开始我最后一个手势 position 结束的手势。

import SwiftUI

struct TestView: View {
    @State var xPosition: CGFloat = 50
    @State var yPosition: CGFloat = 50
    var body: some View {
        VStack{
            Circle()
                .frame(width: 100, height: 100)
                .position(x: xPosition, y: yPosition)
                .gesture(DragGesture()
                    .onChanged{gesture in
                        xPosition = gesture.translation.width
                        yPosition = gesture.translation.height
                    }
                    .onEnded{gesture in
                        xPosition = gesture.translation.width
                        yPosition = gesture.translation.height
                                
                    }
                )
        }
    }
}

struct TestView_Previews: PreviewProvider {
    static var previews: some View {
        TestView()
    }
}

This is the code, let say I make a gesture and move my circle to any given position (works great) but when I try dragging it again the gesture start again from the first position (50,50).这是代码,假设我做一个手势并将我的圆圈移动到任何给定的 position(效果很好)但是当我再次尝试拖动它时,手势再次从第一个 position(50,50)开始。 is there a way to fix it that with GestureState or updating or anything else?有没有办法通过GestureState或更新或其他任何方法来解决它?

Thanks for taking the time to help me out on this one.感谢您花时间帮助我解决这个问题。

The translation is a relative location (equivalent to location.{x,y} - startLocation.{x,y} ). translation是一个相对位置(相当于location.{x,y} - startLocation.{x,y} )。

You should store the position instead, ie您应该改为存储position ,即

struct TestView: View {
    @State var position: CGPoint = CGPoint(x: 50, y: 50)

    var body: some View {
        VStack{
            Circle()
                .frame(width: 100, height: 100)
                .position(position)
                .gesture(
                    DragGesture()
                        .onChanged { gesture in
                            position = gesture.location
                        }
                        .onEnded { gesture in
                            position = gesture.location
                        }
                )
        }
    }
}

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

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