ToggleSwitch.swift 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /// A light switch style control that is either on or off.
  2. ///
  3. /// This corresponds to the ``ToggleStyle/switch`` toggle style.
  4. struct ToggleSwitch: ElementaryView, View {
  5. /// Whether the switch is active or not.
  6. private var active: Binding<Bool>
  7. /// Creates a switch.
  8. ///
  9. /// - Parameter active: Whether the switch is active or not.
  10. public init(isOn active: Binding<Bool>) {
  11. self.active = active
  12. }
  13. func asWidget<Backend: BaseAppBackend>(backend: Backend) -> Backend.Widget {
  14. return backend.createSwitch()
  15. }
  16. func computeLayout<Backend: BaseAppBackend>(
  17. _ widget: Backend.Widget,
  18. proposedSize: ProposedViewSize,
  19. environment: EnvironmentValues,
  20. backend: Backend
  21. ) -> ViewLayoutResult {
  22. let size = ViewSize(backend.naturalSize(of: widget))
  23. return ViewLayoutResult.leafView(size: size)
  24. }
  25. func commit<Backend: BaseAppBackend>(
  26. _ widget: Backend.Widget,
  27. layout: ViewLayoutResult,
  28. environment: EnvironmentValues,
  29. backend: Backend
  30. ) {
  31. backend.updateSwitch(widget, environment: environment) { newActiveState in
  32. if active.wrappedValue != newActiveState {
  33. active.wrappedValue = newActiveState
  34. }
  35. }
  36. backend.setState(ofSwitch: widget, to: active.wrappedValue)
  37. backend.setSize(of: widget, to: layout.size.vector)
  38. }
  39. }