Skip to content

Instantly share code, notes, and snippets.

@hungtrn75
Created October 15, 2020 02:59
Show Gist options
  • Select an option

  • Save hungtrn75/0397fa9ef43e0f26eab0b91210a3c292 to your computer and use it in GitHub Desktop.

Select an option

Save hungtrn75/0397fa9ef43e0f26eab0b91210a3c292 to your computer and use it in GitHub Desktop.
Swift: Pull to Refresh
@available(iOS 13.0, *)
public struct CustomScrollView<Content: View>: UIViewRepresentable {
var size: CGSize
var viewBuilder: () -> Content
var handleRefreshControl: () -> Void
public init(@ViewBuilder viewBuilder: @escaping () -> Content, size: CGSize, handleRefreshControl: @escaping () -> Void) {
self.size = size
self.viewBuilder = viewBuilder
self.handleRefreshControl = handleRefreshControl
}
public func makeCoordinator() -> Coordinator {
Coordinator(self, handleRefreshControl: handleRefreshControl)
}
public func makeUIView(context: Context) -> UIScrollView {
let control = UIScrollView()
control.refreshControl = UIRefreshControl()
control.refreshControl?.addTarget(context.coordinator, action:
#selector(Coordinator.handleRefreshControl),
for: .valueChanged)
return control
}
public func updateUIView(_ control: UIScrollView, context: Context) {
if let child = context.coordinator.child {
child.removeFromParent()
}
let child = UIHostingController(rootView: viewBuilder())
child.view.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
control.addSubview(child.view)
context.coordinator.child = child
}
public class Coordinator: NSObject {
var control: CustomScrollView
var child: UIViewController?
private var _handleRefreshControl: () -> Void
init(_ control: CustomScrollView, handleRefreshControl: @escaping () -> Void) {
self.control = control
self._handleRefreshControl = handleRefreshControl
}
@objc func handleRefreshControl(sender: UIRefreshControl) {
sender.endRefreshing()
_handleRefreshControl()
}
}
}
import SwiftUI
struct ContentView: View {
var body: some View {
GeometryReader{ geometry in
CustomScrollView(viewBuilder: {
Text("Any Content")
}, size: geometry.size) {
print("handle refresh call")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment