Checkbox.swift 1.4 KB

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