ExpandablePicker.swift 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. //
  2. // ExpandablePicker.swift
  3. // LoopKitUI
  4. //
  5. // Created by Anna Quinlan on 8/13/20.
  6. // Copyright © 2020 LoopKit Authors. All rights reserved.
  7. //
  8. import SwiftUI
  9. public protocol Labeled {
  10. var label: String { get }
  11. }
  12. public struct ExpandablePicker<SelectionType: Hashable & Labeled>: View {
  13. @State var pickerShouldExpand = false
  14. var selectedValue: Binding<SelectionType>
  15. let label: String
  16. let items: [SelectionType]
  17. public init (
  18. with items: [SelectionType],
  19. selectedValue: Binding<SelectionType>,
  20. label: String = ""
  21. ) {
  22. self.items = items
  23. self.selectedValue = selectedValue
  24. self.label = label
  25. }
  26. public var body: some View {
  27. VStack(alignment: .leading, spacing: 0) {
  28. HStack(alignment: .center) {
  29. Text(label)
  30. Spacer()
  31. Text(selectedValue.wrappedValue.label)
  32. .foregroundColor(.gray)
  33. }
  34. .padding(.vertical, 5)
  35. .frame(minWidth: 0, maxWidth: .infinity).onTapGesture {
  36. self.pickerShouldExpand.toggle()
  37. }
  38. if pickerShouldExpand {
  39. HStack(alignment: .center) {
  40. Picker(selection: selectedValue, label: Text("")) {
  41. ForEach(items, id: \.self) { item in
  42. Text(item.label)
  43. }
  44. }
  45. .pickerStyle(.wheel)
  46. .labelsHidden()
  47. }
  48. }
  49. }
  50. }
  51. }