2

我正在为一个学校项目制作一个应用程序,我试图计算一个人在不同星球上的重量。ContentView 文件在预览中工作正常,但仅在模拟器/iPhone 中显示 NavigationBar.title。这是代码

import SwiftUI

struct ContentView : View {
    var planets: [Planet] = []
    var body: some View {
        NavigationView {

            List(planets) { planet in
                PlanetCell(planet: planet)
            }
            .navigationBarTitle(Text("Sun"))

        }
    }
}

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

struct PlanetCell : View {
    let planet : Planet
    var body: some View {
        return NavigationLink(destination: PlanetDetail(planet: planet)){
            Text(planet.name)
        }
    }
}

编辑名为 Planet 的 swift 文件

import Foundation
import SwiftUI
struct Planet : Identifiable {
    var id = UUID()
    var name: String
    var g : Float
    var imageName : String { return name }
}

#if DEBUG
let testData = [

    Planet(name: "Mercury", g: 3.724),
    Planet(name: "Venus", g: 8.918),
    Planet(name: "Earth", g: 9.8),
    Planet(name: "Mars", g: 3.724),
    Planet(name: "Jupiter", g: 22.932),
    Planet(name: "Saturn", g: 9.114),
    Planet(name: "Uranus", g: 9.016),
    Planet(name: "Neptune", g: 10.976)

]

#endif


4

3 回答 3

3

实际上,您的代码很好,并且可以执行预期的操作,您的代码testData仅在调试模式下可用(预览版)。这就是为什么您在真实设备或模拟器中看不到它的原因,为了查看实际数据,您需要planetsContentView文件中填充数据数组,因此它应该有一些行星,就像您的testData. 你应该修改你ContentView的如下:

import SwiftUI

struct ContentView : View {
    var planets: [Planet] = [

        Planet(name: "Mercury", g: 3.724),
        Planet(name: "Venus", g: 8.918),
        Planet(name: "Earth", g: 9.8),
        Planet(name: "Mars", g: 3.724),
        Planet(name: "Jupiter", g: 22.932),
        Planet(name: "Saturn", g: 9.114),
        Planet(name: "Uranus", g: 9.016),
        Planet(name: "Neptune", g: 10.976)

    ]
    var body: some View {
        NavigationView {

            List(planets) { planet in
                PlanetCell(planet: planet)
            }
            .navigationBarTitle(Text("Sun"))

        }
    }
}

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

struct PlanetCell : View {
    let planet : Planet
    var body: some View {
        return NavigationLink(destination: PlanetDetail(planet: planet)){
            Text(planet.name)
        }
    }
}

我建议您查看如何使用UIObservableObject并将State其与模型更改绑定,您可以查看本教程:SwiftUI by Example

于 2019-10-12T19:30:08.493 回答
1

在 ContentView 更改

var planets: [Planet] = []

var planets: [Planet] = testData
于 2019-12-20T03:21:44.030 回答
0

初始化时是否将非空列表 ( planets) 传递给您的?ContentView

于 2019-10-12T11:01:15.990 回答