我的列表未显示在模拟器中,但在预览中显示得很好

时间:2020-06-29 15:51:05

标签: swiftui

我用SwiftUI创建了一个列表。我的列表在预览中很好地显示,但在模拟器中却没有:

struct ContentView: View {
    var sandwiches: [Sandwich] = []
    var body: some View {
        NavigationView {
            List(sandwiches) { item in
                NavigationLink(destination: Image(item.name)) {
                    Image(item.name)
                        .resizable()
                        .frame(width: 40, height: 40)
                    VStack(alignment: .leading) {
                        Text(item.name)
                        Text("En Savoir plus...")
                            .font(.subheadline)
                            .foregroundColor(.secondary)
                    }
                }
            }.navigationBarTitle("Sandwiches")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(sandwiches: testData)
    }
}

enter image description here

Xcode 11.5(11E608c)

1 个答案:

答案 0 :(得分:0)

在预览中,您像这样创建ContentView

ContentView(sandwiches: testData)

testData分配给sandwiches中的ContentView属性。

但是,当在真实设备/模拟器上运行时,您的ContentView通常是在SceneDelegate中创建的。

您在ContentView中的SceneDelegate可能是这样创建的:

ContentView()

它不会给您带来任何错误,因为您为sandwiches变量提供了默认参数(编译器允许您跳过它):

var sandwiches: [Sandwich] = []

如果您这样创建ContentView

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        let contentView = ContentView() // <- here you need to pass `sandwiches`

        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        }
    }
    ...
}

您可能还希望将sandwiches参数传递给ContentView中的SceneDelegate(如果SceneDelegate中可用,甚至可以是testData): / p>

ContentView(sandwiches: testData)