Create Segment Control in SwiftUI

SwiftUI’s Picker can also be used to create segmented controls equivalent to UISegmentedControl from UIKit, although it needs to be bound to some state and you must ensure to give each segment a tag so it can be identified. Segments can be text or pictures; anything else will silently fail.

As an example, this creates a segmented control that works with a favoriteNumber state property, and adds a text view below that shows whichever value was selected:

import SwiftUI


struct ContentView: View {

    @State private var favoriteNumber = 0

    var numbers = ["One", "Two", "Three"]

    

    init() {

        UISegmentedControl.appearance().selectedSegmentTintColor = .red

        UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected)

        UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.gray], for: .normal)

    }


    var body: some View {

        VStack {

            Picker(selection: $favoriteNumber, label: Text("What is your favorite color?")) {

                ForEach(0..<numbers.count) { index in

                    Text(self.numbers[index]).tag(index)

                }

            }.pickerStyle(SegmentedPickerStyle())

                .padding()


            Text("Value: \(numbers[favoriteNumber])")

                .foregroundColor(Color.pink)

                .font(.largeTitle)

        }

    }

}


struct ContentView_Previews: PreviewProvider {

    static var previews: some View {

        ContentView()

    }

}


Comments

Popular posts from this blog

PayUMoney Integration in Swift 5

Migrating from UIKit to SwiftUI