问题
This is a simple example of infinity scroll. How add infinity to Up scroll
and insert rows at beginning:
rows.insert(contentsOf: Array(repeating: "Item 0", count: 20), at: 0)
Like apple do this trick in calendar.
struct Screen: View {
@State var rows: [String] = Array(repeating: "Item", count: 20)
private func getNextPageIfNecessary(encounteredIndex: Int) {
guard encounteredIndex == rows.count - 1 else { return }
rows.append(contentsOf: Array(repeating: "Item", count: 20))
}
var body: some View {
...
List(0..<rows.count, id: \.self) { index in
Text(verbatim: self.rows[index])
.onAppear {
self.getNextPageIfNecessary(encounteredIndex: index)
}
}
回答1:
Here is the simplest idea. It is scratchy and of course it can be tuned and improved (like cancelling, better timing, etc.), but the idea remains... Hope it will be helpful somehow.
struct TestInfinityList: View {
@State var items: [Int] = Array(100...120)
@State var isUp = false
var body: some View {
VStack {
HStack {
Button(action: { self.isUp = true }) { Text("Up") }
Button(action: { self.isUp = false }) { Text("Down") }
}
Divider()
List(items, id: \.self) { item in
Text("Item \(item)")
}
.onAppear {
DispatchQueue.main.async {
self.goNext()
}
}
}
}
func goNext() {
self.isUp ? self.moveUp() : self.moveDown()
}
func moveUp() {
self.items.insert(self.items.first! - 1, at: 0)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
self.goNext()
}
}
func moveDown() {
_ = self.items.removeFirst()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
self.items.append(self.items.last! + 1)
self.goNext()
}
}
}
来源:https://stackoverflow.com/questions/59056691/swiftui-infinity-scroll-up-and-down