我有这个自定义视图,可以在SwiftUI中创建滚动视图。我正在尝试检测视图的底部,因此我可以调用load()
函数来加载下一批数据。问题是:
我的实现检测到底部时,不是在到达底部时,而是在以下时间:到达底部,然后拉起屏幕,因此要触发它,我需要比底部做更多的工作。当滚动条位于底部时,没有任何反应。
更奇怪的是,即使只有一个项目,当我拉起(甚至认为没有滚动条)时,也会再次调用load()
。
此外,我的handleRefreshControl(sender: UIRefreshControl)
也很混乱。当我拉起屏幕时,这也会触发。仅应在向下滚动而不向上滚动时触发。
我现在不希望我的函数被调用。
但是在这一点上。因此,当滚动条位于末尾时(甚至在末尾前一点)。
我在做什么错了?
import SwiftUI
struct CustomScrollView<Content: View, VM: LoadProtocol> : UIViewRepresentable {
var width : CGFloat
var height : CGFloat
var viewModel: VM
let content: () -> Content
func makeCoordinator() -> Coordinator {
Coordinator(self, viewModel: viewModel)
}
func makeUIView(context: Context) -> UIScrollView {
let control = UIScrollView()
control.refreshControl = UIRefreshControl()
control.refreshControl?.addTarget(context.coordinator, action: #selector(Coordinator.handleRefreshControl), for: .valueChanged)
control.delegate = context.coordinator
let childView = UIHostingController(rootView: content())
childView.view.frame = CGRect(x: 0, y: 0, width: width, height: height)
control.addSubview(childView.view)
return control
}
func updateUIView(_ uiView: UIScrollView, context: Context) { }
class Coordinator: NSObject, UIScrollViewDelegate {
var control: CustomScrollView<Content, VM>
var viewModel: VM
init(_ control: CustomScrollView, viewModel: VM) {
self.control = control
self.viewModel = viewModel
}
var fetchingMore = false
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (scrollView.contentOffset.y + 1) >= (scrollView.contentSize.height - scrollView.frame.size.height) {
if !fetchingMore {
beginFetchMore()
}
}
}
func beginFetchMore() {
fetchingMore = true
viewModel.load()
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
self.fetchingMore = false
}
}
@objc func handleRefreshControl(sender: UIRefreshControl) {
sender.endRefreshing()
viewModel.refresh()
}
}
}