SwiftUI Gestures RotationGesture

RotationGesture

Rotate views with two fingers using RotationGesture and apply the angle via .rotationEffect.


Syntax

Rotation: Use RotationGesture() to read an Angle and apply it with .rotationEffect(angle).


Rotate and Reset

Rotate the image with two fingers. Releasing animates back to 0°.

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct RotationDemo: View {
  @State private var angle = Angle.zero
  var body: some View {
Image(systemName: "arrow.2.circlepath")
  .font(.system(size: 48))
  .rotationEffect(angle)
  .gesture(
    RotationGesture()
      .onChanged { value in angle = value }
      .onEnded { _ in withAnimation(.easeInOut) { angle = .zero } }
  )
} }

In the example above, the image can be rotated with two fingers.

Releasing animates back to 0°.


Accumulate Rotation

Accumulate the rotation so each gesture adds to the total angle.

Display the angle in degrees.

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct RotationAccumDemo: View {
  @State private var total: Angle = .zero
  @State private var current: Angle = .zero
  var body: some View {
VStack(spacing: 12) {
  Image(systemName: "arrow.triangle.2.circlepath")
    .font(.system(size: 48))
    .rotationEffect(total + current)
    .gesture(
      RotationGesture()
        .onChanged { value in current = value }
        .onEnded { value in total += value; current = .zero }
    )
  Text("Angle: \(Int((total + current).degrees))°")
}
.padding()
} }

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *