Last active
January 7, 2021 10:35
-
-
Save zahmedpk/64c5af162ca0e3563670b4cb17d377d4 to your computer and use it in GitHub Desktop.
Use Coordinate spaces to convert tap location.
This file contains 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
// SwiftUI Coordinate Spaces example | |
// Xcode 12.3 | |
// We show two colored rectangles on screen. When any of these rectangles is tapped | |
// we convert the tap location into VStack's coordinate space and show a circle at | |
// that location. | |
import SwiftUI | |
struct ContentView: View { | |
@State var locationOfTapInStackCoords: CGPoint? { | |
didSet { | |
if locationOfTapInStackCoords != nil { | |
print("location of tap in stack coords is \(locationOfTapInStackCoords!)") | |
} | |
} | |
} | |
static let topLevelStack = "topLevelStack" | |
var body: some View { | |
VStack { | |
GeometryReader { | |
geometry in | |
Color.purple | |
.gesture(DragGesture(minimumDistance: 0, coordinateSpace: .local) | |
.onEnded { (dragGestureValue) in | |
handleTap(at: dragGestureValue.location, usingGeometry: geometry) | |
}) | |
} | |
GeometryReader { | |
geometry in | |
Color.orange | |
.gesture(DragGesture(minimumDistance: 0, coordinateSpace: .local) | |
.onEnded { (dragGestureValue) in | |
handleTap(at: dragGestureValue.location, usingGeometry: geometry) | |
}) | |
} | |
} | |
.coordinateSpace(name: Self.topLevelStack) | |
.overlay(Group{ | |
if locationOfTapInStackCoords != nil { | |
Circle() | |
.stroke(Color.black) | |
.frame(width: 20, height: 20) | |
.position(locationOfTapInStackCoords!) | |
} | |
}) | |
} | |
func handleTap(at location: CGPoint,usingGeometry geometry: GeometryProxy){ | |
locationOfTapInStackCoords = geometry.convert(location, in: CoordinateSpace.named(Self.topLevelStack)) | |
} | |
} | |
extension GeometryProxy { | |
func convert(_ point: CGPoint,in coordinateSpace: CoordinateSpace) -> CGPoint { | |
let frameInOtherCoordinateSpace = self.frame(in: coordinateSpace) | |
let dx = frameInOtherCoordinateSpace.origin.x | |
let dy = frameInOtherCoordinateSpace.origin.y | |
return CGPoint(x: point.x+dx, y: point.y+dy) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment