Last active
January 12, 2021 18:23
-
-
Save schwjustin/71e83480e70ad0589902fd41a980e6c7 to your computer and use it in GitHub Desktop.
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
// | |
// UIScrollViewWrapper.swift | |
// | |
// Created by Justin Schwartz on 12/29/20. | |
// | |
import SwiftUI | |
import UIKit | |
struct UIScrollViewWrapper<Content: View>: UIViewControllerRepresentable { | |
var content: () -> Content | |
func makeUIViewController(context: Context) -> UIScrollViewViewController { | |
let vc = UIScrollViewViewController() | |
vc.hostingController.rootView = AnyView(self.content()) | |
return vc | |
} | |
func updateUIViewController(_ viewController: UIScrollViewViewController, context: Context) { | |
viewController.hostingController.rootView = AnyView(self.content()) | |
} | |
} | |
class UIScrollViewViewController: UIViewController { | |
lazy var scrollView: UIScrollView = { | |
let view = UIScrollView() | |
view.showsVerticalScrollIndicator = false | |
view.alwaysBounceVertical = true | |
return view | |
}() | |
let refreshControl = UIRefreshControl() | |
var hostingController: UIHostingController<AnyView> = UIHostingController(rootView: AnyView(EmptyView())) | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
refreshControl.addTarget(self, action: #selector(didPullToRefresh), for: .valueChanged) | |
self.hostingController.willMove(toParent: self) | |
self.hostingController.view.backgroundColor = .clear | |
self.hostingController.didMove(toParent: self) | |
self.view.addSubview(self.scrollView) | |
self.scrollView.addSubview(refreshControl) | |
self.scrollView.addSubview(self.hostingController.view) | |
self.pinEdges(of: self.scrollView, to: self.view) | |
self.pinEdges(of: self.hostingController.view, to: self.scrollView) | |
} | |
@objc func didPullToRefresh() { | |
// Update your content… | |
// Dismiss the refresh control. | |
DispatchQueue.main.async { | |
self.refreshControl.endRefreshing() | |
} | |
} | |
func pinEdges(of viewA: UIView, to viewB: UIView) { | |
viewA.translatesAutoresizingMaskIntoConstraints = false | |
viewB.addConstraints([ | |
viewA.leadingAnchor.constraint(equalTo: viewB.leadingAnchor), | |
viewA.trailingAnchor.constraint(equalTo: viewB.trailingAnchor), | |
viewA.topAnchor.constraint(equalTo: viewB.topAnchor), | |
viewA.bottomAnchor.constraint(equalTo: viewB.bottomAnchor), | |
]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment