我正在使用SwiftUI。我有一个名为SideBar的视图,它由VStack和其中的按钮组成。
我试图在VStack上附加一些手势,例如DragGesture()
和TapGesture()
onended
,希望它能够检测到用户何时拖动视图,但这并不总是有效,我也认为这超级骇人。
任何人都可以提供帮助吗?非常感谢。
代码:
VStack{blabla}
.frame(width: 40, height: 320)
.contentShape(Rectangle())
.gesture(
TapGesture().onEnded{_ in
print("end click")
}
)
.gesture(
DragGesture().onEnded{_ in
print("end drag")
}
)
仅DragGesture().onChanged(_:)
就足够了。您可以获取更新的拖动值,可以决定如何使用。
在下面的示例中,当拖动VStack
时,捕获的值将重新渲染UI,在该UI中将使用它来确定position
的VStack
。
struct ContentView: View {
@State var position = CGPoint(x: 100, y: 100)
var body: some View {
VStack {
Text("Hello, World")
}
.background(Color.gray)
.position(position)
.gesture(DragGesture()
.onChanged { (value) in
self.position = CGPoint(x: value.location.x,
y: value.location.y)
})
}
}