Created
August 19, 2019 00:41
-
-
Save PaulWoodIII/32a43446714ed4028b35943c80a0bd8b to your computer and use it in GitHub Desktop.
selected items are not selected if the Item type is a reference instead of a value as well
This file contains 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
// | |
// SelectedItems.swift | |
// OrderedList | |
// | |
// Created by Paul Wood on 8/18/19. | |
// Copyright © 2019 Paul Wood. All rights reserved. | |
// | |
import SwiftUI | |
import Combine | |
class Context: ObservableObject { | |
@Published var items: Array<Item> | |
@Published var selectedItems: Set<Item> | |
init() { | |
let a = Item("A") | |
let b = Item("B") | |
let c = Item("C") | |
self.items = [a,b,c] | |
self.selectedItems = Set([a]) | |
} | |
} | |
class Item: Identifiable, Hashable { | |
static func == (lhs: Item, rhs: Item) -> Bool { | |
lhs.id == rhs.id | |
} | |
public var id: UUID = UUID() | |
public var displayText: String | |
init(_ text: String) { | |
self.displayText = text | |
} | |
func hash(into hasher: inout Hasher) { | |
hasher.combine(id) | |
} | |
} | |
struct SelectedItems: View { | |
@ObservedObject var context: Context | |
var body: some View { | |
NavigationView { | |
List (context.items, selection: $context.selectedItems) { item in | |
Text(item.displayText) | |
}.navigationBarTitle("List") | |
.environment(\.editMode, .constant(.active)) | |
} | |
} | |
} | |
#if DEBUG | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
SelectedItems(context: Context()) | |
} | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment