在尝试不经过长按就做出简单的拖动手势时,我发现两种不同的方法似乎可以产生相同的结果。我不确定一种方法是否优于另一种方法,或者两种方法是否同样有效。
在这里,我使用@State CGSize值来表示viewState和dragState
struct Example1: View {
@State var viewState: CGSize = .zero
@State var dragState: CGSize = .zero
var body: some View {
let dragGesture = DragGesture()
.onChanged { (value) in
self.dragState = value.translation
}.onEnded { (value) in
self.viewState.width += value.translation.width
self.viewState.height += value.translation.height
self.dragState = .zero
}
return Circle().foregroundColor(.blue).frame(width: 20, height: 20)
.offset(x: dragState.width + viewState.width,
y: dragState.height + viewState.height)
.gesture(dragGesture)
}
}
这一次,我使结构类似于“撰写SwiftUI手势”文章,但没有长按手势。
struct Example2: View {
@State var viewState: CGSize = .zero
@GestureState var dragState: DragState = .inactive
enum DragState {
case inactive
case active(translation: CGSize)
var translation: CGSize {
switch self {
case .active(translation: let translation):
return translation
default:
return .zero
}
}
}
var body: some View {
let dragGesture = DragGesture()
.updating($dragState) { (value, state, _) in
state = .active(translation: value.translation)
}.onEnded { (value) in
self.viewState.width += value.translation.width
self.viewState.height += value.translation.height
}
return Circle().foregroundColor(.red).frame(width: 20, height: 20)
.offset(x: dragState.translation.width + viewState.width,
y: dragState.translation.height + viewState.height)
.gesture(dragGesture)
}
}
这些实现中的任何一个在我不了解的情况下是否有做任何事情,或者它们完全相同?