UIScrollView in Swift with CanvasView

60 Views Asked by At

With the following code I create a scrollview for an object which in this case is a Rectangle with a CanvasView on it. My first problem is that when I zoom out the view, the object moves more to the left and no longer stays in the middle. If I zoom in, the scrollView becomes so wide that it takes a long time to reach the edge. So my questions are how to keep the object in the middle and how to reduce the border between my inserted object and the border of the scrollView.

import SwiftUI

struct ZoomableScrollView<Content: View>: UIViewRepresentable {
    @State private var screenHeight: CGFloat = UIScreen.main.bounds.height
    
  private var content: Content

  init(@ViewBuilder content: () -> Content) {
    self.content = content()
  }

  func makeUIView(context: Context) -> UIScrollView {
    // set up the UIScrollView
    let scrollView = UIScrollView()
    scrollView.delegate = context.coordinator  // for viewForZooming(in:)
    scrollView.maximumZoomScale = 20
    scrollView.minimumZoomScale = 0.8
    scrollView.bouncesZoom = true
   // scrollView.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    scrollView.contentMode = .center
    scrollView.contentSize = CGSize(width: 200, height: 500)
    
    // create a UIHostingController to hold our SwiftUI content
    let hostedView = context.coordinator.hostingController.view!
    hostedView.translatesAutoresizingMaskIntoConstraints = true
    hostedView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    hostedView.backgroundColor = UIColor(red: 0, green: 1, blue: 0, alpha: 0)
    hostedView.contentMode = .center
      
    scrollView.addSubview(hostedView)

    return scrollView
  }

  func makeCoordinator() -> Coordinator {
    return Coordinator(hostingController: UIHostingController(rootView: self.content))
  }

  func updateUIView(_ uiView: UIScrollView, context: Context) {
    // update the hosting controller's SwiftUI content
    context.coordinator.hostingController.rootView = self.content
    assert(context.coordinator.hostingController.view.superview == uiView)
  }

  // MARK: - Coordinator

  class Coordinator: NSObject, UIScrollViewDelegate {
    var hostingController: UIHostingController<Content>

    init(hostingController: UIHostingController<Content>) {
      self.hostingController = hostingController
    }

    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
      return hostingController.view
    }
  }
}
0

There are 0 best solutions below