swiftui提供了
.gesture(DragGesture().onChanged{
dragAmount = $0.translation
}.onEnded{
_ in
// withAnimation(.spring()){
// dragAmount = .zero
// }
dragAmount = .zero
})
其中onchanged是监听拖动过程中,onEnded是监听拖动结束
struct GestureView: View {
@State private var dragAmount = CGSize.zero
var body: some View {
LinearGradient(gradient: Gradient(colors: [.yellow,.red]), startPoint: .topLeading, endPoint: .bottomTrailing)
.frame(width: 300, height: 200)
.clipShape(RoundedRectangle(cornerRadius: 10))
.offset(dragAmount)
.gesture(DragGesture().onChanged{
dragAmount = $0.translation
}.onEnded{
_ in
// withAnimation(.spring()){
// dragAmount = .zero
// }
dragAmount = .zero
})
.animation(.spring().delay(Double(2 / 20)),value: dragAmount)
}
}
struct GestureView_Previews: PreviewProvider {
static var previews: some View {
GestureView()
}
}