Search code examples
iosswiftswiftuilazyvgrid

LazyVGrid cell subviews keep disappearing for particular text inside cell


Scenario

I am trying to create a 3 columned LazyVGrid which displays items having an icon and a text via a LazyVGrid.

Code

struct CategoryPickerCellPresentationModel: Identifiable {
    let id = UUID()
    let name: String
    let image: Image
    let color: Color
}

extension CategoryPickerCellPresentationModel: Equatable {
    static func == (lhs: CategoryPickerCellPresentationModel, rhs: CategoryPickerCellPresentationModel) -> Bool {
        return lhs.name == rhs.name
    }
}

struct CategoriesListView: View {
    let categorySelectionDatasource: [CategoryPickerCellPresentationModel]
    let gridItemLayout: [GridItem] = Array(repeating: .init(.flexible()), count: 3)
    
    var body: some View {
        ScrollView {
            Spacer(minLength: 20)
            LazyVGrid(columns: gridItemLayout, spacing: 40) {
                ForEach((0..<categorySelectionDatasource.count)) {
                    let category = categorySelectionDatasource[$0]
                    VStack {
                        category.image
                            .font(.system(size: 30))
                            .frame(width: 50, height: 50)
                            .foregroundColor(category.color)
                        Text(category.name)
                            .multilineTextAlignment(.center)
                    }
                }
            }
        }
    }
}

struct CategoriesListView_Previews: PreviewProvider {
    static var previews: some View {
        let dumyCategory = [CategoryPickerCellPresentationModel(name: "Household", image: Image(systemName: "house.fill"), color: .green),
                            CategoryPickerCellPresentationModel(name: "Finance", image: Image(systemName: "banknote.fill"), color: .green), CategoryPickerCellPresentationModel(name: "Education", image: Image(systemName: "book.fill"), color: .purple), CategoryPickerCellPresentationModel(name: "Health", image: Image(systemName: "cross.case.fill"), color: .red)]
        CategoriesListView(categorySelectionDatasource: dumyCategory+dumyCategory.reversed()+dumyCategory)
    }
}

Problem

Whenever the text is Health, I try to scroll the grid, the text disappears. I tried a couple of different texts other than Health, it works great for them.

enter image description here

What could be a possible cause for this?


Solution

  • It is issue of frame remove this line .frame(width: 50, height: 50) and it works. it is not problem with letter Health but it generate same issue when text width less than 50.

    Edit

    if you add id in ForEach loop, works. no need to remove frame.

    ForEach((0..<categorySelectionDatasource.count), id:\.self)