我正在为一个学校项目制作一个应用程序,我试图计算一个人在不同星球上的体重。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)
}
}
}
编辑 - 名为行星的快速文件
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
实际上你的代码很好,可以做它应该做的事情,你的testData
仅在调试模式下可用(预览(。这就是为什么您在真实设备或模拟器中看不到它的原因,为了查看实际数据,您需要在ContentView
文件中填充数据数组planets
,因此它应该像您的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
将 UI 与模型更改绑定,您可以查看本教程: SwiftUI 示例
在内容视图中更改
var planets: [Planet] = []
自
var planets: [Planet] = testData
初始化时是否将非空列表(planets
(传递给ContentView
?