Home Guides Rotation animation

A SwiftUI rotation animation

A SwiftUI rotation animation, the kind that keeps turning, reads degrees off the clock. rotationEffect takes an Angle. The timeline makes a new one every frame.

A sketch of the motion. The file below plays on the phone, and the same source pastes into Xcode.

The file

import SwiftUI

struct SpinningTile: View {
    var body: some View {
        TimelineView(.animation) { context in
            let t = context.date.timeIntervalSinceReferenceDate
            RoundedRectangle(cornerRadius: 14)
                .fill(.orange)
                .frame(width: 54, height: 54)
                .rotationEffect(.degrees(t * 90))
        }
    }
}

t * 90 is degrees per second, so the tile does a full turn every four seconds. .degrees() is the form the player runs. A rounded rectangle with a fill and a frame is enough shape to see the turn. Without the frame, the rectangle has no size.

Clock, not spring

A spring is the right tool when a value is going somewhere: a tap, a toggle, a view arriving. Rotation that continues has nowhere to arrive. Tie it to TimelineView and the angle is just the date, the same way the loading dots are just the date.

rotation3DEffect is the same idea with an axis, when you want a flip instead of a spin in the plane. Start with this file. It pastes into Xcode unchanged.

Keep going

Get Swoop

iPhone. iOS 17 and later. The file plays on the phone.