【问题标题】:SwiftUI - QGrid with static cellsSwiftUI - 带有静态单元格的 QGrid
【发布时间】:2019-08-11 13:15:59
【问题描述】:

我正在使用这个 SwiftUI 包,它允许网格: https://github.com/Q-Mobile/QGrid

我正在尝试制作一个没有数据的简单网格(静态单元格),但出现以下错误。

Xcode 11 测试版 5 Catalina Beta 5

我的代码:


import QGrid
import SwiftUI

struct GridView: View {
var body: some View {
QGrid(columns: 4, { ProductCell() }
}
}

#if DEBUG
struct GridView_Previews : PreviewProvider {
static var previews: some View {
GridView()
}
}
#endif

为什么会出现这样的错误?

【问题讨论】:

    标签: gridview swiftui xcode11 macos-catalina


    【解决方案1】:

    您不能使用该包创建没有数据的网格。如果你看它的代码,只有一个QGrid初始化器,它需要数据。

    这是一个最小的例子:

    import QGrid
    import SwiftUI
    
    struct Item: Identifiable {
        let id = UUID()
        let name: String
    }
    
    struct ContentView: View {
        let array = [Item(name: "Name #1"), Item(name: "Name #2"), Item(name: "Name #3"), Item(name: "Name #4"), Item(name: "Name #5")]
    
        var body: some View {
            QGrid(array, columns: 3) { value in
                MyCell(item: value)
            }
        }
    }
    
    struct MyCell: View {
        let item: Item
    
        var body: some View {
            Text("\(item.name)")
        }
    }
    

    在绘制单元格时,您可以使用虚假数组并忽略数据。但是你需要那个包吗?另请注意,由于array.count,QGrid 知道要绘制多少个单元格。

    这将是一个伪造的数组:

    struct Item: Identifiable { let id = UUID() }
    
    struct ContentView: View {
        let array = Array<Item>(repeating: Item(), count: 5)
    
        var body: some View {
            QGrid(array, columns: 3) { value in
                MyCell()
            }
        }
    }
    

    【讨论】:

    • 更新添加了一个伪造的数组,例如。
    • 谢谢@kontiki!现在将使用您的建议,然后在我设置数据结构时更改。
    猜你喜欢
    • 2017-04-01
    • 1970-01-01
    • 2016-07-13
    • 2019-03-01
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多