SwiftUI Gestures RotationGesture
SwiftUI Gestures: 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
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 } }
)
}
}
import SwiftUI
struct ContentView: View {
var body: some View { RotationDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
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
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()
}
}
import SwiftUI
struct ContentView: View {
var body: some View { RotationAccumDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
In the example above, the image can be rotated with two fingers.
Each gesture adds to the total angle.