Skip to content

Instantly share code, notes, and snippets.

@tatsuz0u
Last active March 11, 2023 16:04
Show Gist options
  • Save tatsuz0u/9beb8d5eb0911480ca31e92d5cfddce0 to your computer and use it in GitHub Desktop.
Save tatsuz0u/9beb8d5eb0911480ca31e92d5cfddce0 to your computer and use it in GitHub Desktop.
//
// MenuPicker.swift
// BitRemote
//
// Created by 荒木辰造 on R 5/03/12.
//
import SwiftUI
struct MenuPicker<Items: RandomAccessCollection, Element: Equatable, ID: Hashable, MenuLabel: View>: View
where Element == Items.Element {
let items: Items
let id: KeyPath<Element, ID>
let title: KeyPath<Element, String>
@Binding var selectedItem: Element?
@ViewBuilder var label: (Element?) -> MenuLabel
var body: some View {
Menu(
content: {
ForEach(items, id: id) { item in
Button {
selectedItem = item
} label: {
if selectedItem == item {
Label(item[keyPath: title], systemImage: "checkmark")
} else {
Text(item[keyPath: title])
}
}
}
},
label: {
label(selectedItem)
}
)
.menuOrder(.fixed)
}
}
extension MenuPicker where Element: Identifiable, ID == Element.ID {
init(
items: Items,
title: KeyPath<Element, String>,
selectedItem: Binding<Element?>,
label: @escaping (Element?) -> MenuLabel
) {
self.items = items
self.id = \Element.id
self.title = title
self._selectedItem = selectedItem
self.label = label
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment