SwiftUI tutorials:Fatal error: No ObservableObject of type DataType found.

错误解决:

SwiftUI tutorials Fatal error: No ObservableObject of type UserData found.
错误记录:
在这里插入图片描述
解决方法:

  • 保证两个点:
  1. 添加.environmentObject(UserData())在两个地方:
  2. 第一个页面的 static var previews:some View{}中
  3. SceneDelagete.swift文件中,let contentView = xxx(你的第一个页面).environmentObject(UserData())

我解决的代码:

// LandmarkList.swift
struct LandmarkList_Previews: PreviewProvider {
    static var previews: some View {
                LandmarkList()
                .previewDevice(PreviewDevice(rawValue: "iPhone 8"))
         .environmentObject(UserData())
         }
         }
//SceneDelegate.swift
  
  func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

        // Create the SwiftUI view that provides the window contents.
        // 这里是重点!!!!
        let contentView = LandmarkList().environmentObject(UserData())

        // Use a UIHostingController as window root view controller.
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值