28

SwiftUI Segmented Control Tutorial

 4 years ago
source link: https://www.tuicool.com/articles/rmE3Q3y
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 segmented control is a set of two or more segments, each of which functions as a mutually exclusive button. In this tutorial a segmented control will be displayed and a text view will be updated with the contents of the selected segment .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 SwiftUISegmentedControlTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next . Choose a location to save the project on your Mac.

JVfIj2r.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.
    @State private var selectorIndex = 0
    @State private var numbers = ["One","Two","Three"]
  
    var body: some View {
        VStack {
            // 2
            SegmentedControl(selection: $selectorIndex) {
                ForEach(0 ..< numbers.count) { index in
                    Text(self.numbers[index]).tag(index)
                }
            }
            // 3.
            Text("Selected value is: \(numbers[selectorIndex])").padding()
        }
    }
}
  1. each item in a selector has a tag value with index number starting at 0.

  2. A segmented control is displayed containing the items from the numbers array.

  3. The selected value in the segmented control is displayed

In the preview pane select the live preview button. Select a segmented control item and the text view will update.

uYzemaN.png!web

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK