2

I'm trying to introspect the UIScrollView under the hood of a SwiftUI ScrollView and that's all fine and dandy.

But I noticed that there were some issues with spacing and animation when scrolling going the pure representable approach so instead I'm trying to leverage a few properties of the underlying UIScrollView via a few bindings that are updates as part of the scrollview delegate.

That's not the main concern, the main issue I'm having even if I'm not doing any bindings at all but a bare bones approach of using the ScrollView in a UIViewRepresentable context is that it behaves differently.

public struct PerfectScrollView<Content: View>: UIViewRepresentable {
    
    private let content: Content
    
    public init(@ViewBuilder content: () -> Content) {
        self.content = content()
    }
    
    public func updateUIView(_ uiView: UIViewType, context: Context) {
    }
    
    public func makeUIView(context: Context) -> UIView {
        UIHostingController(rootView:
        ScrollView {
            content
        }
        ).view
    }
}

// Usage
PerfectScrollView {
  ForEach(0..<100) { Text("Hello \($0)") }
}

// vs
ScrollView {
  ForEach(0..<100) { Text("Hello \($0)") }
}

The result of PerfectScrollView renders this where I'm centered in the middle of the scrollview's content. enter image description here

But the normal ScrollView (not setup via UIViewRepresentable protocol) renders an appropriate scrollview. enter image description here

Any ideas about what actually is happening? From interacting with he PerfectScrollView it's like I've reached the end/bounds of the view and trying to scroll results in the rubber band style resistance animation scrolling up or down.

Any help/feedback would be greatly appreciated :)

Andrew Edwards
  • 1,005
  • 1
  • 9
  • 24
  • 1
    Is there a reason why you use `UIViewRepresentable` instead of `UIViewControllerRepresentable`? – hallo Oct 17 '22 at 21:53
  • @hallo Only because `UIScrollview` is a `UIView` type. Is there any other reason why you'd opt for `UIViewControllerRepresentable`? – Andrew Edwards Oct 18 '22 at 01:04
  • Because in the provided example you use `UIHostingController` and then access its view and when you use `UIViewControllerRepresentable` with `UIHostingController` directly the problem doesn't exist. But I assume the same problem exists when using `UIScrollView` instead of `UIHostingController.view`? – hallo Oct 18 '22 at 06:46
  • I was making an assumption that wasn't true. Using `UIViewControllerRepresentable` protocol actually gives me the behavior I'm looking for. Thanks for the pointer :) @hallo – Andrew Edwards Oct 18 '22 at 13:51

1 Answers1

1

The solution was to use UIViewControllerRepresentable protocol since i was using ScrollView in a UIHostingController context.

Andrew Edwards
  • 1,005
  • 1
  • 9
  • 24