【问题标题】:How do I code the example model object in the PreviewProvider in SwiftUI?如何在 SwiftUI 的 PreviewProvider 中编写示例模型对象?
【发布时间】:2019-07-13 20:46:49
【问题描述】:

我有一些代码,但我没有全部。我了解有关 SwiftUI 和 Core Data 的代码基础知识,但我不知道如何在以下代码中编写 redFox 模型示例。

我尝试自己编写 redFox 代码,但没有成功。

import SwiftUI

struct AnimalCell : View
{
    let model: AnimalCellModel

    var body: some View
    {
        HStack
        {
            Text(model.image)
            Text(model.commonName)
            Text(model.familyName)
            Text(model.scientificName)
        }
    }
}

#if DEBUG
public enum AnimalCellPreviews : PreviewProvider
{
    public static var previews: some View
    {
        AnimalCell(model: .redFox)
    }
}
#endif

我应该看到预览,但因为代码不完整而看不到。

【问题讨论】:

    标签: core-data swiftui


    【解决方案1】:

    不确定这是否是您要求的,但标准预览代码如下:

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

    所以在你的情况下应该是:

    #if DEBUG
    struct AnimalCell_Previews : PreviewProvider {
    
        static var previews: some View {
            AnimalCell(model: RedFox())
        }
    }
    #endif
    

    假设你有一个 RedFox 结构或类

    【讨论】:

    • 不应该是:AnimalCell(model: .redFox)。假设 .redFox 是结构或类,我如何编码 .redFox,而不是 RedFox()。假设 .redFox 是一个结构或类,它的代码是什么样的?
    【解决方案2】:

    您需要将redFox 作为静态属性添加到AnimalCellModel

    extension AnimalCellModel {
        static var redFox = AnimalCellModel(...)
    }
    

    然后您可以将它与 .redFox 语法一起使用,如您的示例中所示。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-23
      • 2014-05-02
      • 2020-03-01
      • 2019-12-26
      • 2010-10-01
      相关资源
      最近更新 更多