Created
July 9, 2020 10:19
-
-
Save EnesKaraosman/d778cdabc98ca269b3d162896bea8aac to your computer and use it in GitHub Desktop.
Single item selection in a list in SwiftUI
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 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