Skip to content

Instantly share code, notes, and snippets.

@rayfix

rayfix/PickerExample.swift

Last active Jan 23, 2021
Embed
What would you like to do?
//
// ContentView.swift
// PickerDemo2
//
// Created by Ray Fix on 1/23/21.
//
import SwiftUI
struct Item {
enum Status: CaseIterable {
case noLongerCarry
case onBackOrder
case inStock
static var gone: [Self] = [.noLongerCarry, .onBackOrder]
var name: LocalizedStringKey {
switch self {
case .noLongerCarry:
return "Don't carry"
case .onBackOrder:
return "Back order"
case .inStock:
return "In stock"
}
}
}
var name: String
var status: Status
}
struct ItemView: View {
@Binding var item: Item
var body: some View {
VStack {
Text(item.name)
Picker("Status", selection: $item.status) {
ForEach(Item.Status.allCases, id: \.self) { status in
Text(status.name).tag(status)
}
}.pickerStyle(SegmentedPickerStyle())
}
}
}
struct ReadOnlyItemView: View {
let item: Item
var body: some View {
VStack {
Text(item.name)
Picker("Status", selection: .constant(item.status)) {
ForEach(Item.Status.allCases, id: \.self) { status in
Label(status.name, systemImage: "star").tag(status)
}
}.pickerStyle(SegmentedPickerStyle())
}
}
}
final class ItemsViewModel: ObservableObject {
@Published var items: [Item]
init(items: [Item]) {
self.items = items
}
}
struct ItemsView: View {
@ObservedObject var viewModel: ItemsViewModel
var body: some View {
NavigationView {
Form {
ForEach(viewModel.items.indices, id: \.self) { index in
ItemView(item: $viewModel.items[index])
}
}
}
}
}
struct ContentView: View {
@StateObject var model = ItemsViewModel(items: [
.init(name: "Power Rangers", status: .inStock),
.init(name: "Legos", status: .noLongerCarry),
.init(name: "Slinky", status: .onBackOrder)
])
var body: some View {
ItemsView(viewModel: model)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment