Skip to main content

How to rotate a view

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to rotate a view 관련

SwiftUI by Example

Back to Home

How to rotate a view | SwiftUI by Example

How to rotate a view

Updated for Xcode 15

SwiftUI’s rotationEffect() modifier lets us rotate views freely, using either degrees or radians.

For example, if you wanted to rotate some text by -90 degrees so that it reads upwards, you would use this:

Text("Up we go")
    .rotationEffect(.degrees(-90))

Download this as an Xcode projectopen in new window

The text “Up we go” rotated 90 degrees counter-clockwise.
The text “Up we go” rotated 90 degrees counter-clockwise.

If you prefer using radians, just pass in .radians() as your parameter, like this:

Text("Up we go")
    .rotationEffect(.radians(.pi))

Download this as an Xcode projectopen in new window

The text “Up we go” upside down.
The text “Up we go” upside down.

View rotation is so fast that it’s effectively free, so you could even make it interactive using a slider if you wanted:

struct ContentView: View {
    @State private var rotation = 0.0

    var body: some View {
        VStack {
            Slider(value: $rotation, in: 0...360)

            Text("Up we go")
                .rotationEffect(.degrees(rotation))
        }
    }
}

Download this as an Xcode projectopen in new window

By default views rotate around their center, but if you want to pin the rotation from a particular point you can add an extra parameter for that. For example if you wanted to make the slider above pivoting the rotation around the view’s top-left corner you’d write this:

struct ContentView: View {
    @State private var rotation = 0.0

    var body: some View {
        VStack {
            Slider(value: $rotation, in: 0...360)

            Text("Up we go")
                .rotationEffect(.degrees(rotation), anchor: .topLeading)
        }
    }
}

Download this as an Xcode projectopen in new window

Similar solutions…
How to rotate a view in 3D | SwiftUI by Example

How to rotate a view in 3D
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks
How to convert a SwiftUI view to an image | SwiftUI by Example

How to convert a SwiftUI view to an image
How to make a view dismiss itself | SwiftUI by Example

How to make a view dismiss itself
How to create and compose custom views | SwiftUI by Example

How to create and compose custom views

이찬희 (MarkiiimarK)
Never Stop Learning.