I am using SwiftData and SwiftUI in my application. I have an ExpenseType enum with few cases. I am displaying these cases in segmented control but for some reason I cannot see the selected option in segmented control. Do you see something that I am missing?
enum ExpenseType: String, Codable, CaseIterable, Identifiable {
case business, personal
var id: ExpenseType { self }
var title: String {
switch self {
case .business:
return "Business"
case .personal:
return "Personal"
}
}
}
@Model
class ExpenseItem: Identifiable {
var name: String
var type: ExpenseType
init(name: String, type: ExpenseType) {
self.name = name
self.type = type
}
}
struct ContentView: View {
@State private var selectedExpenseType: ExpenseType = .business
var body: some View {
VStack {
Picker("Select expense type", selection: $selectedExpenseType) {
HStack {
ForEach(ExpenseType.allCases) { expenseType in
Text(expenseType.title)
.tag(expenseType)
}
}
}.pickerStyle(.segmented)
}
.padding()
}
}
Do not wrap the picker options in an HStack
. The picker will treat this as one single option that does not have a tag
, and therefore no option is selected.
Picker("Select expense type", selection: $selectedExpenseType) {
ForEach(ExpenseType.allCases) { expenseType in
Text(expenseType.title)
.tag(expenseType)
}
}.pickerStyle(.segmented)