Last active
January 23, 2021 19:44
-
-
Save rayfix/ed02927bce0d645911b578edf5379baf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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