【问题标题】:A custom View works, but its preview does not compile自定义视图有效,但其预览无法编译
【发布时间】:2021-08-21 20:34:49
【问题描述】:

关于我在 Github 准备的a simple test project 的问题:

它是一个带有自定义 View TopRow.swift 的 SwiftUI 列表:

struct TopRow: View {
    let top:TopEntity
    
    var body: some View {
        HStack {
            Circle()
                .frame(width: 60, height: 60)
            Spacer()
            Text(top.given ?? "Unknown Person")
                .frame(minWidth: 60, maxWidth: .infinity, alignment: .leading)
            Spacer()
            VStack {
                Text("Elo rating: \(top.elo)")
                Text("Average time: \(top.avg_time ?? "")")
                Text("Average score: \(String(top.avg_score))")
            }.fixedSize(horizontal: true, vertical: false)
        }.font(.footnote)
    }
}

正如您在上面的屏幕截图中看到的那样,它工作正常。

但是它的预览不起作用:

struct TopRow_Previews: PreviewProvider {
    static var topEntity = TopEntity(context: PersistenceController.preview.container.viewContext)
    topEntity.uid = 19265
    topEntity.elo = 2659
    topEntity.given = "Alex"
    topEntity.motto = "TODO"
    topEntity.photo = "https://slova.de/words/images/female_happy.png"
    topEntity.avg_score = 18.8
    topEntity.avg_time = "03:06"

    static var previews: some View {
        TopRow(top: topEntity)
            .padding()
            .previewLayout(.sizeThatFits)
    }
}

Xcode 报语法错误Consecutive declarations on a line must be separated by ';'

那里发生了什么,请帮助我(一个 Swift 新手)理解。

我曾尝试在此处放一个分号,但它并没有真正起作用。

【问题讨论】:

    标签: swift core-data swiftui swiftui-list swiftui-previews


    【解决方案1】:

    您不能将这样的命令式代码放在 structclass 的顶层——顶层保留用于函数和属性的声明。

    您可以改为将 topEntity 设为计算属性 - 这样您的命令式分配就可以进入 { } 内部而不存在于顶层:

    struct TopRow_Previews: PreviewProvider {
        static var topEntity : TopEntity {
            var topEntity = TopEntity(context: PersistenceController.preview.container.viewContext)
            topEntity.uid = 19265
            topEntity.elo = 2659
            topEntity.given = "Alex"
            topEntity.motto = "TODO"
            topEntity.photo = "https://slova.de/words/images/female_happy.png"
            topEntity.avg_score = 18.8
            topEntity.avg_time = "03:06"
            return topEntity
        }
    
        static var previews: some View {
            TopRow(top: topEntity)
                .padding()
                .previewLayout(.sizeThatFits)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 2015-07-16
      • 2019-03-28
      • 1970-01-01
      • 1970-01-01
      • 2018-08-26
      • 2020-05-01
      相关资源
      最近更新 更多