SwiftUI Rotate View Tutorial

Views can be rotated in SwiftUI with the .rotationEffect modifier. In this tutorial a system image will be rotated with a preselected number of degrees from a slider. SwiftUI requires Xcode 11 and MacOS Catalina, for which the Betas can be downloaded at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select the Single View App template, and then click Next. Enter SwiftUIRotateViewTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.

In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to

struct ContentView: View {
    // 1.
    @State var rotation: Double = 0
    var body: some View {
        VStack {
            // 2.
            Slider(value: $rotation, in: 0.0...360.0, step: 1.0)
            // 3.
            Image(systemName: "sun.max")
  1. A state property is declared which will represent the degrees of the rotation

  2. A slider is displayed, which can be used to change the rotation degrees

  3. A system image is displayed and rotated with the .rotationEffect modifier

Go to the preview pane and select the live view button. Drag the slider to rotate the image.

The source code of the SwiftUIRotateViewTutorial can be downloaded at the ioscreator repository on Github.