Created
July 8, 2023 00:13
-
-
Save klein-artur/f7f47163a830fdfd597a71bbadc75f91 to your computer and use it in GitHub Desktop.
SwiftUI Selectable List
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
struct Selectables<Data, ID: Hashable, Content>: View where Content: View { | |
let data: [Data] | |
@Binding var selectedIds: [ID] | |
let id: KeyPath<Data, ID> | |
let content: (Data, Binding<Bool>) -> Content | |
init(_ data: [Data], selectedIds: Binding<[ID]>, id: KeyPath<Data, ID>, @ViewBuilder content: @escaping (Data, Binding<Bool>) -> Content) { | |
self.data = data | |
self._selectedIds = selectedIds | |
self.id = id | |
self.content = content | |
} | |
var body: some View { | |
ForEach(data.indices, id: \.self) { index in | |
self.content(self.data[index], Binding( | |
get: { self.selectedIds.contains(self.data[index][keyPath: self.id]) }, | |
set: { isSelected in | |
if isSelected { | |
self.selectedIds.append(self.data[index][keyPath: self.id]) | |
} else { | |
self.selectedIds.removeAll(where: { $0 == self.data[index][keyPath: self.id] }) | |
} | |
} | |
)) | |
} | |
} | |
} | |
extension Selectables where ID == Data.ID, Data: Identifiable { | |
init(_ data: [Data], selectedIds: Binding<[ID]>, @ViewBuilder content: @escaping (Data, Binding<Bool>) -> Content) { | |
self.init(data, selectedIds: selectedIds, id: \Data.id, content: content) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment