How it works
RotationGesture is a gesture recognizer that tracks the angle between two fingers as they rotate around a common center, reporting the rotation as an Angle. Reach for it when you want a view to respond to the iOS two-finger twist, such as rotating an image, a dial, or a card under direct manipulation. Because it conforms to Gesture, you attach it to a view with the gesture(_:) modifier and read its value through the callbacks that every gesture provides, letting you drive rotation state without managing touch math yourself.
Create the recognizer with RotationGesture()
The initializer takes no required arguments and produces a gesture whose value is an Angle measured from the rotation's starting orientation. It begins reporting once enough rotational movement accumulates to distinguish a twist from other touches. In the example,
RotationGesture()is constructed inline and handed straight to the view that should rotate.Attach it with the gesture(_:) modifier
A RotationGesture does nothing until it is bound to a view, which establishes where its two-finger input is recognized. The
.gesture(...)modifier installs the recognizer on theText("Rotate me")card so twisting over that view's bounds feeds the gesture.Read the live angle with onChanged
Calling
.onChangedon the gesture registers a closure that runs continuously as the rotation updates, handing you the current Angle as itsvalue. Here the closure assignsangle = value, so the@Stateproperty follows the fingers in real time while the twist is in progress.Apply the gesture's value through rotationEffect(_:)
RotationGesture only measures the angle; you decide what it transforms. Feeding the stored
angleinto.rotationEffect(angle)rotates the card visually, and readingangle.degreesin the secondTextshows the same value as a number, demonstrating that the gesture's Angle is the single source of truth.
.onEnded { _ in angle = Angle.zero } after .onChanged so the card springs back to its original orientation the moment you lift your fingers, revealing the difference between RotationGesture's in-progress and completed phases.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 RotationGestureDemo: View {
@State private var angle = Angle.zero
var body: some View {
VStack {
Text("Rotate me")
.font(.headline)
.padding(40)
.background(Color.blue.opacity(0.2))
.cornerRadius(12)
.rotationEffect(angle)
.gesture(
RotationGesture()
.onChanged { value in
angle = value
}
)
Text("\(Int(angle.degrees))\u00b0")
.foregroundColor(.secondary)
}
.padding()
}
}