ios_app/Shared/Components/RefreshableScrollView.swift
2025-07-16 07:44:16 +03:00

72 lines
2.8 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import SwiftUI
import UIKit
struct RefreshableScrollView<Content: View>: UIViewRepresentable {
var content: Content
var onRefresh: (UIRefreshControl) -> Void
var isRefreshing: Binding<Bool>
init(isRefreshing: Binding<Bool>, onRefresh: @escaping (UIRefreshControl) -> Void, @ViewBuilder content: () -> Content) {
self.content = content()
self.onRefresh = onRefresh
self.isRefreshing = isRefreshing
}
func makeUIView(context: Context) -> UIScrollView {
let scrollView = UIScrollView()
// Создаем UIRefreshControl и добавляем его
let refreshControl = UIRefreshControl()
refreshControl.addTarget(context.coordinator, action: #selector(Coordinator.handleRefresh), for: .valueChanged)
scrollView.refreshControl = refreshControl
// Создаем хостинг для нашего SwiftUI контента
let hostingController = UIHostingController(rootView: content)
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(hostingController.view)
// Настраиваем Auto Layout
NSLayoutConstraint.activate([
hostingController.view.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor),
hostingController.view.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor),
hostingController.view.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor),
hostingController.view.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor),
hostingController.view.widthAnchor.constraint(equalTo: scrollView.frameLayoutGuide.widthAnchor)
])
context.coordinator.hostingController = hostingController
return scrollView
}
func updateUIView(_ uiView: UIScrollView, context: Context) {
// Обновляем состояние индикатора
if isRefreshing.wrappedValue {
uiView.refreshControl?.beginRefreshing()
} else {
uiView.refreshControl?.endRefreshing()
}
// Обновляем SwiftUI View, если нужно
context.coordinator.hostingController?.rootView = content
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject {
var parent: RefreshableScrollView
var hostingController: UIHostingController<Content>?
init(_ parent: RefreshableScrollView) {
self.parent = parent
}
@objc func handleRefresh(_ sender: UIRefreshControl) {
parent.isRefreshing.wrappedValue = true
parent.onRefresh(sender)
}
}
}