You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI创建的列表预览正常但模拟器不显示(附代码)求助

解决SwiftUI列表预览正常但模拟器不显示的问题

嗨,我一眼就发现问题所在啦!你的预览能正常加载列表,是因为预览代码里特意给ContentView传了testData,但模拟器运行时,你根本没给视图传入任何数据——ContentView里的sandwiches默认是空数组[],空数组的列表当然啥也显示不出来咯。

下面给你两种简单的解决方式:

方式一:给属性设置默认测试数据

直接把ContentView里的sandwiches默认值从空数组改成testData,这样不管是预览还是模拟器运行,都会自动加载测试数据:

struct ContentView: View {
    // 修改这里的默认值
    var sandwiches: [Sandwich] = testData
    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")
        }
    }
}

方式二:在应用入口处传入数据

如果你的testData是全局定义的,也可以在SceneDelegate(Xcode 11的项目结构)中初始化ContentView时手动传入数据,这种方式更适合后续替换成真实接口数据的场景:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // 初始化ContentView时传入testData
    let contentView = ContentView(sandwiches: testData)
    
    // 原有代码...
    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: contentView)
        self.window = window
        window.makeKeyAndVisible()
    }
}

额外需要确认的细节

  1. 确保Sandwich结构体已经正确实现了Identifiable协议,否则List无法正确遍历元素:
struct Sandwich: Identifiable {
    let id = UUID()
    let name: String
    // 其他自定义属性...
}
  1. 确认testData是正确初始化的数组,比如:
// 全局定义测试数据
let testData: [Sandwich] = [
    Sandwich(name: "Club Sandwich"),
    Sandwich(name: "Ham & Cheese"),
    Sandwich(name: "Turkey Avocado")
]

按照上面的方法修改后,模拟器里的列表就能正常显示内容啦!

内容的提问来源于stack exchange,提问作者darksh3ll

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 09:18:13