【问题标题】:LazyVGrid cell subviews keep disappearing for particular text inside cell对于单元格内的特定文本,LazyVGrid 单元格子视图不断消失
【发布时间】:2020-10-29 09:50:41
【问题描述】:

场景

我正在尝试创建一个 3 列的 LazyVGrid,它通过 LazyVGrid 显示具有图标和文本的项目。

代码

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

问题

只要文本是Health,我尝试滚动网格,文本就会消失。除了Health,我尝试了几个不同的文本,这对他们很有效。

这可能是什么原因?

【问题讨论】:

    标签: ios swift swiftui lazyvgrid


    【解决方案1】:

    这是frame 的问题删除此行.frame(width: 50, height: 50) 并且它有效。字母Health 没有问题,但是当text 宽度小于50 时会产生同样的问题。

    编辑

    如果您在 ForEach 循环中添加 id,则可以。无需移除框架。

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

    【讨论】:

    • 谢谢,达瓦尔。奇怪的是,SwiftUI 为何没有剪切或截断文本,而不是让它消失。我觉得这是一个可重用性和优化的问题。
    • 即使在实现中,数据模型也符合可识别的。 SwiftUI 需要数据模型是可识别的,否则除非你像你所做的那样传递一个明确的 id。因此,理想情况下,两者都应该完成这项工作。你觉得有什么不同吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    • 2021-12-09
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多