Skip to content

Instantly share code, notes, and snippets.

@EnesKaraosman
Created July 9, 2020 10:19
Show Gist options
  • Save EnesKaraosman/d778cdabc98ca269b3d162896bea8aac to your computer and use it in GitHub Desktop.
Save EnesKaraosman/d778cdabc98ca269b3d162896bea8aac to your computer and use it in GitHub Desktop.
Single item selection in a list in SwiftUI
struct SingleSelectionList<Item: Identifiable, Content: View>: View {
var items: [Item]
@Binding var selectedItem: Item?
var rowContent: (Item) -> Content
var body: some View {
List(items) { item in
rowContent(item)
.modifier(CheckmarkModifier(checked: item.id == self.selectedItem?.id))
.contentShape(Rectangle())
.onTapGesture {
self.selectedItem = item
}
}
}
}
struct CheckmarkModifier: ViewModifier {
var checked: Bool = false
func body(content: Content) -> some View {
Group {
if checked {
ZStack(alignment: .trailing) {
content
Image(systemName: "checkmark")
.resizable()
.frame(width: 20, height: 20)
.foregroundColor(.green)
.shadow(radius: 1)
}
} else {
content
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment