Skip to content

Instantly share code, notes, and snippets.

@mishimay
Created November 11, 2022 07:03
Show Gist options
  • Save mishimay/e7cdb08f65fd1297a62ffd6abdf9e8b7 to your computer and use it in GitHub Desktop.
Save mishimay/e7cdb08f65fd1297a62ffd6abdf9e8b7 to your computer and use it in GitHub Desktop.
struct MyScrollView<Content: View>: UIViewRepresentable {
let axis: Axis
@ViewBuilder let content: () -> Content
class Coordinator: NSObject, UIScrollViewDelegate {
var hostingController: UIHostingController<Content>?
}
func makeCoordinator() -> Coordinator {
Coordinator()
}
func makeUIView(context: Context) -> UIScrollView {
let scrollView = UIScrollView()
scrollView.delegate = context.coordinator
scrollView.contentInsetAdjustmentBehavior = .never
let hostingController = UIHostingController(rootView: content())
context.coordinator.hostingController = hostingController
if let contentView = hostingController.view {
contentView.backgroundColor = .clear
scrollView.addSubview(contentView)
contentView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
contentView.leftAnchor.constraint(equalTo: scrollView.leftAnchor),
contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
contentView.rightAnchor.constraint(equalTo: scrollView.rightAnchor)
])
switch axis {
case .vertical:
NSLayoutConstraint.activate([
contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor)
])
case .horizontal:
NSLayoutConstraint.activate([
contentView.heightAnchor.constraint(equalTo: scrollView.heightAnchor)
])
}
}
return scrollView
}
func updateUIView(_ uiView: UIScrollView, context: Context) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment