47

SwiftUI Rotation Gesture Tutorial

 4 years ago
source link: https://www.tuicool.com/articles/m2imyiU
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

The Rotation gesture uses can be used to rotate an object .In this tutorial an image is displayed which can be rotated using this gesture..SwiftUI requires Xcode 11 and MacOS Catalina, which can be download 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 SwiftUIRotateGestureTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next . Choose a location to save the project on your Mac.

fAVba2I.png!web

Download theimage, open the Assets library and drag the image to it.

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

QF3Ibe3.png!web

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

struct ContentView: View {
    // 1.
    @State private var rotateState: Double = 0
    
    var body: some View {
        // 2.
        Image("apple_swift_logo")
            // 3.
            .rotationEffect(Angle(degrees: self.rotateState))
            // 4.
            .gesture(RotationGesture()
                .onChanged { value in
                    self.rotateState = value.degrees
                }
            )
    }
}
  1. A state propery is declared, which keeps track of the current rotation degree.

  2. An image is displayed.

  3. The rotatationEffect modifier will rotate the image with the current degree of rotation

  4. A magnification gesture is created, where the current degree of rotation is assigned to the rotateState when the rotation changes.

Go to the preview window. Click the Live preview button. Hold the option key and drag the mouse to rotate the image.

uMvquey.png!web

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK