SwiftUI Gesture Tutorial
source link: https://www.tuicool.com/articles/R3QfqaA
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.
Gestures can be added to any ordinary view in SwiftUI. In this tutorial a tap gesture is added to a text view to change the background color.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 SwiftUIGestureTutorial 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 private var didTap: Bool = false var body: some View { // 2. Text("Tap me") .frame(minWidth:0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity) // 3. .gesture(TapGesture() .onEnded { self.didTap.toggle() } ) // 4. .background(didTap ? Color.blue : Color.red) } }
-
A State property is declared which will track if a tap gesture is detected.
-
A text view is created which will span the entire window using the frame modifier
-
a gesture modifier will toggle the boolean value of the state property
-
The background color is changed according of the current state of the didTap property.
Go to the preview pane and click the live view button. Tap the text to change the background color.
The source code of the SwiftUIGestureTutorial can be downloaded at the ioscreator repository on Github .
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK