SwiftUI 无限滚动(上下) [英] SwiftUI Infinity scroll (up and down)

查看:74
本文介绍了SwiftUI 无限滚动(上下)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个无限滚动的简单例子.如何为向上滚动添加无穷大
并在开头插入行:

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)
                               }
                       }

推荐答案

这是最简单的想法.它很粗糙,当然可以调整和改进(例如取消、更好的时机等),但这个想法仍然存在......希望它会以某种方式有所帮助.

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()
        }
    }
}

这篇关于SwiftUI 无限滚动(上下)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆