How it works
A SpatialEventCollection is the set of active spatial touch events that a SpatialEventGesture reports as a single, indexable group. Each member describes one in-flight input — its identity, phase, and location — so you can react to several concurrent touches at once rather than tracking them individually. Reach for it whenever a gesture handler needs to know not just that input occurred, but how many distinct events are happening and where, such as for multi-finger or multi-pointer interactions on touch and spatial surfaces.
Receive the collection from SpatialEventGesture
A
SpatialEventCollectionis never constructed directly; it arrives as the value passed to the closures of aSpatialEventGesture. In the example,SpatialEventGesture()is attached with.gesture(...), and its update closures hand you the live collection to inspect.Read activity through onChanged
The
.onChangedclosure fires every time the set of active events changes — a touch begins, moves, or lifts. Here the closure binds the incomingSpatialEventCollectionascollection, giving you the current snapshot of all events the moment anything shifts.Count the active events with count
Because
SpatialEventCollectionbehaves like a collection, members such ascounttell you how many spatial events are presently active. The example storescollection.countintocountso theTextcan display "Active events: \(count)" as fingers or pointers come and go.Detect the end of interaction with onEnded
When all events finish,
.onEndedruns. The collection is no longer needed there — the example ignores it with_and resetscount = 0, marking that no spatial events remain on theRoundedRectangle.Iterate events for per-touch detail
Beyond
count,SpatialEventCollectionconforms toCollection, so you can loop over it to read each event's identity, phase, and location. The example only uses the count, but the samecollectionvalue lets you walk every active event when you need to position UI under each touch.
.onChanged, replace count = collection.count with a loop over collection that prints each event's location, then place two or three fingers on the "Touch me" card to watch every active event reported at once.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct SpatialEventCollectionDemo: View {
@State private var count = 0
var body: some View {
VStack(spacing: 12) {
Text("Active events: \(count)")
.font(.headline)
RoundedRectangle(cornerRadius: 16)
.fill(.blue.opacity(0.2))
.frame(width: 160, height: 160)
.overlay(Text("Touch me"))
.gesture(
SpatialEventGesture()
.onChanged { collection in
count = collection.count
}
.onEnded { _ in
count = 0
}
)
}
.padding()
}
}