Andrew Edwards
Andrew Edwards

Reputation: 1025

SwiftUI ScrollView not properly setting content offset when nested in UIViewRepresentable

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 :)

Upvotes: 2

Views: 1050

Answers (1)

Andrew Edwards
Andrew Edwards

Reputation: 1025

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

Upvotes: 1

Related Questions