代码之家  ›  专栏  ›  技术社区  ›  user2555515

SwiftUI表格中的无限滚动

  •  0
  • user2555515  · 技术社区  · 4 年前

    SwiftUI提供了LazyVStack,可以在滚动时动态加载数据。然而,在以下代码中,我找不到任何类似的表,在这些表中,这样的未来会更有用:

    struct BlobView: View {
           var table: some View {
            Table(self.blobs, selection: $selection, sortOrder: $sortOrder) {
                TableColumn("Name", value: \.name) { blob in
                    Text(blob.name)
                }
                TableColumn("Create Time") { blob in
                    let text = blob.createdTime.formatted(date: .abbreviated, time: .shortened)
                    Text(String(text))
                }
                TableColumn("Size") { blob in
                    Text(String(blob.GetBlobSize().formatted()))
                }
                TableColumn("Version") { blob in
                    Text(String(blob.version.formatted()))
                }
            }
        }
    }
    var body: some View {
            table .....
    }
    

    当滚动接近极值点时,是否有方法按需添加加载/卸载数据?

    0 回复  |  直到 4 年前
        1
  •  0
  •   user2555515    4 年前

    事实上,它看起来很简单:原始问题中的self.blobs(作为参数传递给Table构造函数)应该实现RandomAccessCollection。然后表格会自动无限滚动。

        struct Blobs: RandomAccessCollection {
        var startIndex: Int { 0 }
        var endIndex: Int { 1000 }
        func formIndex(after i: inout Int) { i += 1 }
        func formIndex(before i: inout Int) { i -= 1 }
    
        subscript(index: Int) -> Blob {
            //Demo only, in working application get blob from cache if the index misses refresh from db
            print(index)
            return Blob(id: UUID(), name: "\(index)",
                        description: "description")
        }```