SwiftUI:手势和偏移未按预期工作

Geo*_*Lee 4 offset gesture swiftui

我正在使用偏移量和手势修饰符在屏幕上移动一个圆圈。当我使用此代码时,一切都按预期工作:

import SwiftUI

struct MovingCircle: View {

@State private var dragged = CGSize.zero

var body: some View {
    Circle()
        .offset(x: self.dragged.width)
        .frame(width: 20, height: 20)
        .gesture(DragGesture()
            .onChanged{ value in
                self.dragged = value.translation
        }
        .onEnded{ value in
            self.dragged = CGSize.zero
            }
    )
 }
}
Run Code Online (Sandbox Code Playgroud)

但是,我不想将圆圈重置为 onEnded 的原始位置。我希望它保持原位,然后在拖动时再次移动。当我使用以下代码时,我无法在重新拖动时再次移动圆圈并且它保持原位:

import SwiftUI

struct MovingCircle: View {

@State private var dragged = CGSize.zero

var body: some View {
    Circle()
        .offset(x: self.dragged.width)
        .frame(width: 20, height: 20)
        .gesture(DragGesture()
            .onChanged{ value in
                self.dragged = value.translation
        }
        .onEnded{ value in
            self.dragged = value.translation
            }
    )
}
}
Run Code Online (Sandbox Code Playgroud)

这是什么原因,我是否遇到了一些错误或我编码不正确?

kon*_*iki 8

首先,要了解问题,.border(Color.red).frame()修饰符中添加一个:

.frame(width: 20, height: 20).border(Color.red)
Run Code Online (Sandbox Code Playgroud)

你会看到当点移动时,它的框架保持在原位。这就是为什么以后它不会响应手势的原因。“可点击”区域不再与点匹配。并且因为内容区域现在是空的,它不再是“可点击的”。

要使框架随点移动,请颠倒顺序。本.offset()应该晚一点:

.frame(width: 20, height: 20).border(Color.red)
.offset(x: self.dragged.width)
Run Code Online (Sandbox Code Playgroud)

最后,您会看到在每个 之后.onEnded(),整个事情都重置了。解决它的一种方法是累积您在以前的手势中拖动的数量:

struct MovingCircle: View {

    @State private var dragged = CGSize.zero
    @State private var accumulated = CGSize.zero

    var body: some View {
        Circle()
            .frame(width: 20, height: 20).border(Color.red)
            .offset(x: self.dragged.width)

            .gesture(DragGesture()
                .onChanged{ value in
                    self.dragged = CGSize(width: value.translation.width + self.accumulated.width, height: value.translation.height + self.accumulated.height)
            }
            .onEnded{ value in
                self.dragged = CGSize(width: value.translation.width + self.accumulated.width, height: value.translation.height + self.accumulated.height)
                self.accumulated = self.dragged
                }
        )
    }
}
Run Code Online (Sandbox Code Playgroud)