Skip to content

Commit 68ff3fe

Browse files
authored
SelectionState can apply environment values to passed body view (#34)
1 parent 9302056 commit 68ff3fe

File tree

2 files changed

+26
-9
lines changed

2 files changed

+26
-9
lines changed

Sources/CollectionView/SelectableForEach.swift

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -33,17 +33,13 @@ public struct SelectableForEach<
3333
public var body: some View {
3434
ForEach(IndexedCollection(data)) { element in
3535

36-
let isSelected: Bool = selection.isSelected(for: element.id)
36+
let isSelected: Bool = selection.isSelected(for: element.value.id)
3737
let isDisabled: Bool = !selection.isEnabled(for: element.id)
3838

39-
cell(element.index, element.value)
40-
.disabled(isDisabled)
41-
.environment(\.collectionView_isSelected, isSelected)
42-
.environment(
43-
\.collectionView_updateSelection,
44-
{ [selection] isSelected in
45-
selection.update(isSelected: isSelected, for: element.value)
46-
})
39+
selection.applyEnvironments(
40+
for: cell(element.index, element.value),
41+
item: element.value
42+
)
4743
}
4844
}
4945

Sources/CollectionView/SelectionState.swift

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import SwiftUI
12

23
public enum SelectAction {
34
case selected
@@ -18,6 +19,26 @@ public protocol SelectionState<Item> {
1819
func update(isSelected: Bool, for item: Item)
1920
}
2021

22+
extension SelectionState {
23+
24+
public func applyEnvironments<Body: View>(for body: Body, item: Item) -> some View {
25+
26+
let isSelected: Bool = isSelected(for: item.id)
27+
let isDisabled: Bool = !isEnabled(for: item.id)
28+
29+
return body
30+
.disabled(isDisabled)
31+
.environment(\.collectionView_isSelected, isSelected)
32+
.environment(
33+
\.collectionView_updateSelection,
34+
{ isSelected in
35+
self.update(isSelected: isSelected, for: item)
36+
}
37+
)
38+
}
39+
40+
}
41+
2142
extension SelectionState {
2243

2344
public static func single<Item: Identifiable>(

0 commit comments

Comments
 (0)