我正在为一个学校项目制作一个应用程序,试图计算一个人在不同星球上的体重。 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的快速文件
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
答案 0 :(得分:2)
实际上,您的代码很好,并且可以执行预期的工作,您的testData
仅在调试模式下可用(预览)。这就是为什么您没有在真实设备或模拟器中看到它的原因,为了查看实际数据,您需要在planets
文件中填充数据数组ContentView
,因此其中应该有一些行星就像您的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)
}
}
}
我建议您了解如何使用ObservableObject
和State
将用户界面与模型更改绑定在一起,您可以查看本教程:SwiftUI by Example
答案 1 :(得分:0)
初始化时,您是否将非空列表(planets
)传递给ContentView
?
答案 2 :(得分:0)
在ContentView中更改
var planets: [Planet] = []
到
var planets: [Planet] = testData