错误解决:
SwiftUI tutorials Fatal error: No ObservableObject of type UserData found.
错误记录:
解决方法:
- 保证两个点:
- 添加.environmentObject(UserData())在两个地方:
- 第一个页面的 static var previews:some View{}中
- 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()
}
}