Skip to content

Instantly share code, notes, and snippets.

@ericlewis
Last active February 22, 2022 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericlewis/1dc24d743e699b5002863d2cfdecd306 to your computer and use it in GitHub Desktop.
Save ericlewis/1dc24d743e699b5002863d2cfdecd306 to your computer and use it in GitHub Desktop.
import SwiftUI
import swiftui_betterpicker
struct GridPickerView: View {
enum Colors: CaseIterable {
case red
case blue
case green
case purple
case yellow
case pink
var color: Color {
switch self {
case .red: return .red
case .purple: return .purple
case .green: return .green
case .yellow: return .yellow
case .blue: return .blue
case .pink: return .pink
}
}
}
@State
private var selection = Colors.red
var body: some View {
_Picker("Grid", selection: $selection) {
ForEach(Colors.allCases, id: \.self) {
$0.color.tag($0)
}
}
.pickerStyle(.grid)
.navigationTitle("Grid Picker")
}
}
extension _PickerStyle where Self == GridPickerStyle {
static var grid: GridPickerStyle { .init() }
}
struct GridPickerStyle: _PickerStyle {
func makeBody(configuration: Configuration) -> some View {
Style(configuration: configuration)
}
struct Style: View {
let configuration: Configuration
var body: some View {
LazyVGrid(columns: [.init(), .init(), .init()]) {
configuration.content {
.init(makeOption($0, $1))
}
}
}
@ViewBuilder
func makeOption(
_ option: Configuration.Option,
_ tag: _Tag
) -> some View {
switch tag {
case let .tagged(tag):
Button {
withAnimation {
configuration.selection = tag
}
} label: {
option
.aspectRatio(1, contentMode: .fit)
.overlay {
if configuration.selection == tag {
Image(systemName: "checkmark.circle.fill")
.imageScale(.large)
.foregroundColor(.primary)
}
}
}
.buttonStyle(.plain)
case .untagged:
EmptyView()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment