Toggle.swift 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /// A control for toggling between two values (usually representing on and off).
  2. ///
  3. /// Depending on the value of ``EnvironmentValues/toggleStyle``, this control
  4. /// can appear as a switch, a button, or a checkbox.
  5. public struct Toggle: View {
  6. @Environment(\.backend) var backend
  7. @Environment(\.toggleStyle) var toggleStyle
  8. /// The label to be shown on or beside the toggle.
  9. var label: String
  10. /// Whether the toggle is active or not.
  11. var active: Binding<Bool>
  12. @available(*, deprecated, renamed: "init(_:isOn:)")
  13. public init(_ label: String, active: Binding<Bool>) {
  14. self.init(label, isOn: active)
  15. }
  16. /// Creates a toggle that displays a custom label.
  17. ///
  18. /// - Parameters:
  19. /// - label: The label to be shown on or beside the toggle.
  20. /// - active: Whether the toggle is active or not.
  21. public init(_ label: String, isOn active: Binding<Bool>) {
  22. self.label = label
  23. self.active = active
  24. }
  25. public var body: some View {
  26. switch toggleStyle.style {
  27. case .switch:
  28. HStack {
  29. Text(label)
  30. if backend.requiresToggleSwitchSpacer {
  31. Spacer()
  32. }
  33. ToggleSwitch(isOn: active)
  34. }
  35. case .button:
  36. ToggleButton(label, isOn: active)
  37. case .checkbox:
  38. HStack {
  39. Text(label)
  40. Checkbox(isOn: active)
  41. }
  42. }
  43. }
  44. public var _asMenuItems: [MenuItem] {
  45. [.toggle(self)]
  46. }
  47. }
  48. /// A style of toggle.
  49. public struct ToggleStyle: Sendable {
  50. @_spi(Backends) public var style: Style
  51. /// A toggle switch.
  52. public static let `switch` = Self(style: .switch)
  53. /// A toggle button. Generally looks like a regular button when off and an
  54. /// accented button when on.
  55. public static let button = Self(style: .button)
  56. /// A checkbox.
  57. public static let checkbox = Self(style: .checkbox)
  58. @_spi(Backends) public enum Style: Sendable {
  59. case `switch`
  60. case button
  61. case checkbox
  62. }
  63. }