Last active
May 15, 2024 08:36
-
-
Save benigumocom/839d9de13be4b0698020e73ab1ea2da9 to your computer and use it in GitHub Desktop.
【SwiftUI】View を ドラッグ して移動 する 👉 https://android.benigumo.com/20240514/drag-view/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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