Responding to gestures: Rotating

Responding to gestures: Rotating

Discover how to respond to rotation gestures in a SwiftUI app.

When creating interactions triggered by rotation movements in SwiftUI, use the RotateGesture. It recognizes when the users place two fingers over an item and rotate them.

RotateGesture(minimumAngleDelta: .degrees(30))

When setting up the gesture, you can specify a minimum angle delta for activation using the minimumScaleDelta property. The default value is 1 degree.

To add an action to be performed when the gesture’s value changes, use the onChanged(_:) instance method. In the example below the value of the view’s property currentAngle is updated with the rotation value of the gesture.

RotateGesture()
    .onChanged { value in
        currentAngle = value.rotation
    }

To associate the gesture with a view, use the modifier gesture(_:including:). In the examples below, the rotate gesture will work alongside the rotationEffect(_:anchor:) modifier rotate the view accordingly.

struct ContentView: View {
    
    @State private var currentAngle = Angle(degrees: 45.0)
    
    var body: some View {
        Capsule()
            .fill(.blue)
            .frame(width: 200, height: 100, alignment: .center)
        
            .rotationEffect(currentAngle)
            .gesture(
                RotateGesture(minimumAngleDelta: Angle(degrees: 10))
                    .onChanged { value in
                        currentAngle = value.rotation
                    }
            )
    }
}