Created
October 15, 2020 02:59
-
-
Save hungtrn75/0397fa9ef43e0f26eab0b91210a3c292 to your computer and use it in GitHub Desktop.
Swift: Pull to Refresh
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
| @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() | |
| } | |
| } | |
| } |
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 | |
| 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