.onDrag
Last updated
Last updated
// ๐view.onDrag(changed: {}, ended: {})
extension View {
public func onDrag(
changed: @escaping (DragGesture.Value) -> Void,
ended : @escaping (DragGesture.Value) -> Void
) -> some View {
let drag = DragGesture().onChanged(changed).onEnded(ended)
return self.gesture(drag)
}
}
import SwiftUI
import PlaygroundSupport
struct ContentView: View {
// โญ๏ธ drag state
@State private var translation = CGSize.zero
var body: some View {
VStack {
Circle()
.fill(Color.pink)
.frame(44, 44) // ๐view.frame(w,h)
// โญ๏ธ 2. follow drag
.offset(translation)
// โญ๏ธ 1. update state
.onDrag( // ๐view.onDrag(changed: {}, ended: {})
changed: { self.translation = $0.translation },
ended : { _ in self.translation = .zero }
)
}// container
.frame(400, 300)
.padding()
.shadow(radius: 8)
.background(Color.gray)
.cornerRadius(10)
}
}
PlaygroundPage.current.setLiveView(ContentView())
struct ContentView: View {
// โญ๏ธ drag state
@State private var translation = CGSize.zero
var body: some View {
VStack {
Circle()
.fill(Color.pink)
.frame(44, 44) // ๐View + frame(w,h)
// โญ๏ธ 3. follow drag
.offset(translation)
.gesture(
DragGesture()
// โญ๏ธ 1. update state
.onChanged { self.translation = $0.translation }
// โญ๏ธ 2. reset (return to the original place)
.onEnded { _ in self.translation = .zero }
)
}// container
.frame(400, 300)
.padding()
.shadow(radius: 8)
.background(Color.gray)
.cornerRadius(10)
}
}
SwiftUI โฉ Views & Controls โฉ Views โฉ Input and Events