firebase 是否可以在没有“懒惰”修改器的情况下创建“懒惰VGrid”?

hgc7kmma  于 2023-02-13  发布在  其他
关注(0)|答案(1)|浏览(118)

我正在从我的Firebase后端加载数据,“懒惰”的部分使我的应用程序看起来有问题/冻结一样,向下滚动时,它严重滞后...
是否可以创建一个“没有懒惰功能”的VGrid??(iOS 14)
如果没有,除了完全抛弃网格之外,还有什么建议吗?

let layout = [
    GridItem(.flexible()),
    GridItem(.flexible()),

]

@ObservedObject var homeModel = Home_ViewModel()

NavigationView(content: {
        
        ScrollView() {
            LazyVGrid(columns: layout, spacing: 10) {
                ForEach(homeModel.projectList) { item in
                    
                    ProjectItemWidget(
                        projectID: item.id,
                        projectTitle: item.projectTitle,
                        projectAuthorProfileImage: item.authorProfileImageUrl,
                        projectAuthor: item.projectAuthor)
                }
            }
            .padding(.trailing, 7.5)
        }
}
ix0qys7i

ix0qys7i1#

我一直在苦苦思考一个不使用LazyVGrid就可以创建网格布局的解决方案,并得出了以下结论:

extension Array {
    func getElementAt(index: Int) -> Element? {
        return (index < self.endIndex) ? self[index] : nil
    }
}

struct CustomGridLayout<Element, GridCell>: View where GridCell: View {

    private var array: [Element]
    private var numberOfColumns: Int
    private var gridCell: (_ element: Element) -> GridCell
        
    init(_ array: [Element], numberOfColumns: Int, @ViewBuilder gridCell: @escaping (_ element: Element) -> GridCell) {
        self.array = array
        self.numberOfColumns = numberOfColumns
        self.gridCell = gridCell
    }
        
        var body: some View {
            Grid {
                ForEach(Array(stride(from: 0, to: self.array.count, by: self.numberOfColumns)), id: \.self) { index in
                    GridRow {
                        ForEach(0..<self.numberOfColumns, id: \.self) { j in
                            if let element = self.array.getElementAt(index: index + j) {
                                self.gridCell(element)
                            }
                        }
                    }
                }
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
        }
    }

在视图中使用的示例:

struct ContentView: View {
    private var array: [Int] = Array(1...7)
    
    var body: some View {
        CustomGridLayout(array, numberOfColumns: 3) { element in
            RoundedRectangle(cornerRadius: 10)
                .foregroundColor(.orange)
                .overlay(alignment: .center) {
                    Text("\(element)")
                }
        }
        .padding(.horizontal)
    }
}

您可以在以下链接中查看结果:https://i.stack.imgur.com/1o7ip.png

相关问题