Skip to content

Instantly share code, notes, and snippets.

@mishimay
Created July 15, 2019 05:50
Show Gist options
  • Save mishimay/81beb17814949a9305ad4f5022a38ae5 to your computer and use it in GitHub Desktop.
Save mishimay/81beb17814949a9305ad4f5022a38ae5 to your computer and use it in GitHub Desktop.
Bridge UIScrollView to SwiftUI
struct MyScrollView: UIViewRepresentable {
let swiftUIView: AnyView
func makeUIView(context: UIViewRepresentableContext<ContentView.MyScrollView>) -> UIView {
let hosting = UIHostingController(rootView: swiftUIView)
let width = UIScreen.main.bounds.width
let size = hosting.view.sizeThatFits(CGSize(width: width, height: CGFloat.greatestFiniteMagnitude))
hosting.view.frame = CGRect(x: 0, y: 0, width: width, height: size.height)
let view = UIScrollView()
view.alwaysBounceVertical = true
view.addSubview(hosting.view)
view.contentSize = CGSize(width: width, height: size.height)
return view
}
func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<ContentView.MyScrollView>) {
}
}
@ZachOrr
Copy link

ZachOrr commented Mar 9, 2020

You could make this more SwiftUI-ish by using a ViewBuilder in the initalizer. Ex:

struct MyScrollView<Content>: UIViewRepresentable where Content : View {

    let content: () -> Content

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

    func makeUIView(context: UIViewRepresentableContext<ContentView.MyScrollView>) -> UIView {
        let hosting = UIHostingController(rootView: content())
        // ...
    }

}

@danhalliday
Copy link

Any idea how to make this work when the scroll view contains dynamic content? (Eg. a ForEach loop fed from a property @State var items = [...] which changes over time?

@deep-randhawa
Copy link

@mishimay @danhalliday were you guys able to figure out how to make this work with dynamically changing content?

@danhalliday
Copy link

@deep-randhawa It can be done but I’m afraid I’ve forgotten the details. I’ve seen the solution posted around the web — if you search for more custom ScrollView implementations you’ll find it. Basically you need to update the whole view in updateUIView.

@pavermakov
Copy link

@danhalliday do you have a link?

@mishimay
Copy link
Author

I wrote an improved code.
Please check this.
https://gist.github.com/mishimay/b823280bd91d16474362376029321752

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment