SwiftUI Infinity scroll (up and down)

三世轮回 提交于 2021-02-08 06:34:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!