struct PickerExample: View { @State private var selected = 0 var body: some View { Picker("Choose course", selection: $selected) { Text("SwiftUI") .tag(0) Text("UIKit") .tag(1) } .pickerStyle(.segmented) } }
struct PickerExample: View { @State private var selected = "SwiftUI" var body: some View { Picker("Choose course", selection: $selected) { Text("SwiftUI") .tag("SwiftUI") Text("UIKit") .tag("UIKit") } .pickerStyle(.segmented) } }
enum Category: String { case swiftUI = "SwiftUI" case uIKit = "UIKit" }struct PickerExample: View { @State private var selected = Category.swiftUI var body: some View { Picker("Choose course", selection: $selected) { Text(Category.swiftUI.rawValue) .tag(Category.swiftUI) Text(Category.uIKit.rawValue) .tag(Category.uIKit) } .pickerStyle(.segmented) } }
struct PickerExample: View { @State private var selected = "SwiftUI" let segments = ["SwiftUI", "UIKit", "ML", "CV"] var body: some View { Picker("Choose course", selection: $selected) { ForEach(segments, id:\.self) { segment in Text(segment) .tag(segment) } } .pickerStyle(.segmented) } }
struct PickerExample: View { @State private var selected = "SwiftUI" let segments = ["SwiftUI", "UIKit", "ML", "CV"] var body: some View { Picker("Choose course", selection: $selected) { ForEach(segments, id:\.self) { segment in Text(segment) .tag(segment) } } .pickerStyle(.segmented) .background(Color.orange) .cornerRadius(50) .padding() } }
struct CustomSegmentedPickerView: View { @State private var selection = 0 private var titles = ["SwiftUI", "UIKit", "ML", "CV"] private var colors = [Color.purple, Color.blue, Color.pink, Color.green] @State private var frames = Array<CGRect>(repeating: .zero, count: 4) var body: some View { VStack { ZStack { HStack(spacing: 10) { ForEach(self.titles.indices, id: \.self) { index in Button(action: { self.selection = index }) { Text(self.titles[index]) .foregroundColor(.white) }.padding(EdgeInsets(top: 16, leading: 20, bottom: 16, trailing: 20)).background( GeometryReader { geo in Color.clear.onAppear { self.setFrame(index: index, frame: geo.frame(in: .global)) } } ) } } .background( Capsule().fill( self.colors[self.selection].opacity(0.4)) .frame(width: self.frames[self.selection].width, height: self.frames[self.selection].height, alignment: .topLeading) .offset(x: self.frames[self.selection].minX - self.frames[0].minX) , alignment: .leading ) } .animation(.default, value: selection) .background(Capsule().stroke(Color.purple, lineWidth: 3)) Text("Value: \(self.titles[self.selection])") .font(.largeTitle) Picker(selection: self.$selection, label: Text("What is your favorite color?")) { ForEach(0..<self.titles.count) { index in Text(self.titles[index]).tag(index) } }.pickerStyle(SegmentedPickerStyle()) } } func setFrame(index: Int, frame: CGRect) { self.frames[index] = frame } }
With that we have reached the end of this article. Thank you once again for reading. Don’t forget to subscribe to our weekly newsletter at