【问题标题】:Lazy loading SwiftUI Grid on both vertical and horizontal direction在垂直和水平方向上延迟加载 SwiftUI Grid
【发布时间】:2022-11-15 12:25:31
【问题描述】:

正如标题所说,我尝试构建一个在垂直和水平上延迟加载的网格视图,主要目标是为员工列表构建日历,列表和日历间隔都可能非常大,因此必须渲染它们懒洋洋。我尝试过LazyHGridLazyVGrid,但它们只在一个方向上懒惰地渲染视图。进一步的方法对整个视图使用一个LazyVStack,对每一行使用一个LazyHStack,加载是惰性的(在控制台中检查打印)但是在滚动视图时会丢失它们的位置并且网格会被破坏

struct ContentView: View {
    var body: some View {
        ScrollView([.horizontal, .vertical]) {
            LazyVStack(spacing: 20, pinnedViews: .sectionHeaders) {
                Section(header: columnHeaders) {
                    ForEach(0..<20) { row in
                        LazyHStack(spacing: 20, pinnedViews: .sectionHeaders) {
                            Section(header: rowHeader(with: "Employee \(row)")) {
                                ForEach(0..<100) { column in
                                    Text("Cell \(row), \(column)")
                                        .foregroundColor(.white)
                                        .font(.largeTitle)
                                        .frame(width: 200, height: 100)
                                        .background(Color.red)
                                        .onAppear {
                                            print("Cell \(row), \(column)")
                                        }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    var columnHeaders: some View {
        LazyHStack(spacing: 20, pinnedViews: .sectionHeaders) {
            Section(header: rowHeader(with: "")) {
                ForEach(0..<100) { column in
                    Text("Header \(column)")
                        .frame(width: 200, height: 100)
                        .background(Color.white)
                }
            }
        }
    }
    
    func rowHeader(with label: String) -> some View {
        Text(label)
            .frame(width: 100, height: 100)
            .background(Color.white)
    }
    
}

PS:我还需要固定的标头,这是在上面的代码中使用pinnedViews 实现的

【问题讨论】:

    标签: ios swift gridview swiftui


    【解决方案1】:

    您可以使用一对嵌套的单轴 ScrollView 而不是一个多轴 ScrollView 来解决对齐问题。

    【讨论】:

      猜你喜欢
      • 2015-10-15
      • 1970-01-01
      • 2020-09-23
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 2019-01-13
      • 2020-11-05
      • 1970-01-01
      相关资源
      最近更新 更多