34

SwiftUI Slider Tutorial

 4 years ago
source link: https://www.tuicool.com/articles/7zyAFbf
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.

A Slider object is a visual control used to select a single value from a continuous range of values. Sliders are always displayed as horizontal bars. An indicator, or thumb indicates the current value of the slider and can be moved by the user to change the setting. In this tutorial, a Slider and a Text view will be displayed. When moving the slider, the corresponding value will be displayed inside the Text view. In this tutorial .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 SwiftUISliderTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next . Choose a location to save the project on your Mac.

iABVbmU.png!web

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.0
    @State var sliderValue = 0.0
    var minimumValue = 0.0
    var maximumvalue = 100.0
    
    var body: some View {
        VStack {
            HStack {
                Text("\(Int(minimumValue))")
                // 2.
                Slider(value: $sliderValue, from: minimumValue, through: maximumvalue, by: 10)
                Text("\(Int(maximumvalue))")
            }.padding()
            // 3.
            Text("\(Int(sliderValue))")
        }
    }
}
  1. A state property is created which containts the current slider value

  2. A Slider is displayed with a value of 0-100. The startvalue is 0.

  3. When the slider value changes, the text field is updated with the new value.

In the preview pane select the live view. change the slider to a new value and the text field will update.

AbAFV3n.png!web

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK