Created
March 17, 2020 10:57
-
-
Save aronbalog/2fade2ae3f9fa61dff0854aa661d20a6 to your computer and use it in GitHub Desktop.
UIScrollView Wrapper for SwiftUI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
public struct ScrollViewWrapper<Content: View>: UIViewRepresentable { | |
@Binding var contentOffset: CGPoint | |
let content: () -> Content | |
public init(contentOffset: Binding<CGPoint>, @ViewBuilder _ content: @escaping () -> Content) { | |
self._contentOffset = contentOffset | |
self.content = content | |
} | |
public func makeUIView(context: UIViewRepresentableContext<ScrollViewWrapper>) -> UIScrollView { | |
let view = UIScrollView() | |
view.delegate = context.coordinator | |
let controller = UIHostingController(rootView: content()) | |
controller.view.sizeToFit() | |
view.addSubview(controller.view) | |
view.contentSize = controller.view.bounds.size | |
return view | |
} | |
public func updateUIView(_ uiView: UIScrollView, context: UIViewRepresentableContext<ScrollViewWrapper>) { | |
uiView.contentOffset = self.contentOffset | |
} | |
public func makeCoordinator() -> Coordinator { | |
Coordinator(contentOffset: self._contentOffset) | |
} | |
public class Coordinator: NSObject, UIScrollViewDelegate { | |
let contentOffset: Binding<CGPoint> | |
init(contentOffset: Binding<CGPoint>) { | |
self.contentOffset = contentOffset | |
} | |
public func scrollViewDidScroll(_ scrollView: UIScrollView) { | |
contentOffset.wrappedValue = scrollView.contentOffset | |
} | |
} | |
} |
one more thing layoutIfNeeded must be called before returing the view because otherwise the view may freeze when updating the content in the scrollView
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was helpful for me, though I had an issue with it updating when content was changed. I added a few lines so that UIHostingController is properly updated on changes: