coordinateSpace
Assigns a name to the view's coordinate space, so other code can operate on dimensions like points and sizes relative to the named space.
Declaration
compose().coordinateSpace(name: SwiftUI.NamedCoordinateSpace)nonisolated func coordinateSpace(
_ name: NamedCoordinateSpace
) -> some ViewParameters
A name used to identify this coordinate space.
Discussion
Use coordinateSpace(_:) to allow another function to find and
operate on a view and operate on dimensions relative to that view.
The example below demonstrates how a nested view can find and operate on its enclosing view's coordinate space:
struct ContentView: View {
@State private var location = CGPoint.zero
var body: some View {
VStack {
Color.red.frame(width: 100, height: 100)
.overlay(circle)
Text("Location: \(Int(location.x)), \(Int(location.y))")
}
.coordinateSpace(.named("stack"))
}
var circle: some View {
Circle()
.frame(width: 25, height: 25)
.gesture(drag)
.padding(5)
}
var drag: some Gesture {
DragGesture(coordinateSpace: .named("stack"))
.onChanged { info in location = info.location }
}
}Here, the VStack in the ContentView named “stack” is composed of a
red frame with a custom Circle view View.overlay(_:alignment:)
at its center.
The circle view has an attached DragGesture that targets the
enclosing VStack's coordinate space. As the gesture recognizer's closure
registers events inside circle it stores them in the shared location
state variable and the VStack displays the coordinates in a Text
view.
See also
More in Drawing and shapes.
- blendModeSets the blend mode for compositing this view with overlapping views.
- buttonBorderShapeSets the border shape for buttons in this view.
- clipShapeSets a clipping shape for this view.
- containerShapeSets the container shape to use for any container relative shape within this view.
- contentShapeSets the content shape for this view.
- materialActiveAppearanceSets an explicit active appearance for materials in this view.
- textInputBorderShapeSets the border shape for text input controls in the view hierarchy.