A simple utility to assist with loading more content in a ScrollView
in SwiftUI.
Add .shouldLoadMore
to any ScrollView
. By default it will be triggered when the content at the bottom of the ScrollView
is close to being in view.
If you want to see it in a real app, check out dateit
Also works well with SwiftUI-Refresher
First add the package to your project.
import ScrollViewLoader
struct ContentView: View {
@State var data: [Int] = Array(0..<1)
var body: some View {
ScrollView {
LazyVStack {
ForEach(data, id: \.self) { i in
Text("\(i)")
.font(.title)
.frame(maxWidth: .infinity)
}
ProgressView()
.scaleEffect(2)
}
}
.shouldLoadMore {
await Task.sleep(seconds: 0.05)
data.append(data.last! + 1)
}
}
}
By default, the callback will be triggered when distance to the bottom of the scrollable content is less than 50%
of the visible hight of the scroll view. You can customize this
Set the relative offset to 20%
instead of the default 50%
:
.shouldLoadMore(bottomDistance: .relative(0.2)) {
// Load more
}
Set the absolute offset to a fixed value:
.shouldLoadMore(bottomDistance: .absolute(200)) {
// Load more
}
waitForHeightChange
It may be desirable for shouldLoadMore
to be called whenever the user scrolls - even if the scroll view content didn't change. You can change this behavior with waitForHeightChange
:
.shouldLoadMore(waitForHeightChange: .never) {
// Will be called regardless of if the content height changed from a previous update
}
.shouldLoadMore(waitForHeightChange: .always) {
// Will only be called if the content height changed since last time
}
.shouldLoadMore(waitForHeightChange: .until(2)) {
// Will only be called if the content height changed since last time or after 2 seconds of no change
}
By default waitForHeightChange
is .until(2)
so the function doesn't get called in quick succession when no content updates are made.
async
.shouldLoadMore { done in
loadYourContent {
data.append(data.last! + 1)
done() // Call done so shouldLoadMore can be called again later
}
}
Larger batching
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。