Skip to content

Instantly share code, notes, and snippets.

@benigumocom
Last active May 15, 2024 08:36
Show Gist options
  • Save benigumocom/839d9de13be4b0698020e73ab1ea2da9 to your computer and use it in GitHub Desktop.
Save benigumocom/839d9de13be4b0698020e73ab1ea2da9 to your computer and use it in GitHub Desktop.
【SwiftUI】View を ドラッグ して移動 する 👉 https://android.benigumo.com/20240514/drag-view/
import SwiftUI
struct TestDragGesture: View {
@State private var location = CGPoint(x: 150, y: 150)
@State private var startLocation: CGPoint?
var body: some View {
Circle()
.fill(.orange)
.frame(width: 200)
.position(location)
.gesture(
DragGesture()
.onChanged { drag in
startLocation = startLocation ?? location
location = CGPoint(
x: startLocation!.x + drag.translation.width,
y: startLocation!.y + drag.translation.height
)
}
.onEnded { _ in
startLocation = nil
}
)
}
}
#Preview {
TestDragGesture()
}
import SwiftUI
struct TestDragGesture: View {
@State private var location = CGPoint(x: 150, y: 150)
@State private var diff: CGPoint?
var body: some View {
Circle()
.fill(.orange)
.frame(width: 200)
.position(location)
.gesture(
DragGesture()
.onChanged { drag in
diff = diff ?? CGPoint(
x: location.x - drag.location.x,
y: location.y - drag.location.y
)
location.x = drag.location.x + diff!.x
location.y = drag.location.y + diff!.y
}
.onEnded { _ in
diff = nil
}
)
}
}
#Preview {
TestDragGesture()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment