PageControl.swift


  1. import SwiftUI
  2. import UIKit
  3. struct PageControl: UIViewRepresentable {
  4. var numberOfPages: Int
  5. @Binding var currentPage: Int
  6. func makeCoordinator() -> Coordinator {
  7. Coordinator(self)
  8. }
  9. func makeUIView(context: Context) -> UIPageControl {
  10. let control = UIPageControl()
  11. control.numberOfPages = numberOfPages
  12. control.addTarget(
  13. context.coordinator,
  14. action: #selector(Coordinator.updateCurrentPage(sender:)),
  15. for: .valueChanged)
  16. return control
  17. }
  18. func updateUIView(_ uiView: UIPageControl, context: Context) {
  19. uiView.currentPage = currentPage
  20. }
  21. class Coordinator: NSObject {
  22. var control: PageControl
  23. init(_ control: PageControl) {
  24. self.control = control
  25. }
  26. @objc
  27. func updateCurrentPage(sender: UIPageControl) {
  28. control.currentPage = sender.currentPage
  29. }
  30. }
  31. }