仅当我开始在要拖动的视图顶部拖动时才拖动手势
Drag gesture only if I start dragging on top of the view that I want to be dragged
我希望仅当我开始拖动该视图时才拖动该视图。目前,如果我从屏幕上的任意位置开始拖动,然后在其上拖动,它就会拖动。
import SwiftUI
struct ContentView: View {
@State private var offset = CGSize.zero
var body: some View {
Text("Hello, world!")
.offset(offset)
.gesture(
DragGesture()
.onChanged { gesture in
offset = gesture.translation
}
.onEnded { _ in
offset = CGSize.zero
}
)
}
}
这是一个可能的解决方案。在您希望可拖动的视图后面放置一个视图,例如 Color
。如果您错过了您真正想要拖动的视图,请在上面放置一个 DragGesture
以捕获拖动。这必须是将显示在屏幕上的视图,否则这不起作用,即您不能使用 Color.clear
.
struct ContentView: View {
@State private var offset = CGSize.zero
var body: some View {
ZStack {
// Place a Color behind your view, set to the background color.
// It can't be clear as that doesn't work.
Color.white
// Place a DragGesture there to capture the drag if not on the view you want
.gesture(DragGesture())
Text("Hello, world!")
.offset(offset)
.gesture(
DragGesture()
.onChanged { gesture in
offset = gesture.translation
}
.onEnded { _ in
offset = CGSize.zero
}
)
}
}
}
我希望仅当我开始拖动该视图时才拖动该视图。目前,如果我从屏幕上的任意位置开始拖动,然后在其上拖动,它就会拖动。
import SwiftUI
struct ContentView: View {
@State private var offset = CGSize.zero
var body: some View {
Text("Hello, world!")
.offset(offset)
.gesture(
DragGesture()
.onChanged { gesture in
offset = gesture.translation
}
.onEnded { _ in
offset = CGSize.zero
}
)
}
}
这是一个可能的解决方案。在您希望可拖动的视图后面放置一个视图,例如 Color
。如果您错过了您真正想要拖动的视图,请在上面放置一个 DragGesture
以捕获拖动。这必须是将显示在屏幕上的视图,否则这不起作用,即您不能使用 Color.clear
.
struct ContentView: View {
@State private var offset = CGSize.zero
var body: some View {
ZStack {
// Place a Color behind your view, set to the background color.
// It can't be clear as that doesn't work.
Color.white
// Place a DragGesture there to capture the drag if not on the view you want
.gesture(DragGesture())
Text("Hello, world!")
.offset(offset)
.gesture(
DragGesture()
.onChanged { gesture in
offset = gesture.translation
}
.onEnded { _ in
offset = CGSize.zero
}
)
}
}
}