致命错误:找不到SelectedTab类型的ObservableObject.SelectedTab的View.envi



此处出现错误-selectedTab=tab.getTab((

致命错误:找不到SelectedTab类型的ObservableObject。SelectedTab的View.environmentObject(_:(可能作为此视图的祖先而丢失。

也尝试过这个-https://www.hackingwithswift.com/forums/swiftui/fatal-error-no-observableobject-of-type-order-found/3208

class SelectedTab: ObservableObject {
@Published var tab:String = "Home"

func setTab(tabName: String) {
tab = tabName
}

func getTab() -> String {
return tab
}
}



struct TabBarContentView: View {
@EnvironmentObject var tab: SelectedTab

var body: some View {
Home().environmentObject(tab)
}
}

struct TabBarContentView_Previews: PreviewProvider {


static var previews: some View {
Group {
TabBarContentView()
.previewDevice(PreviewDevice(rawValue: "iPhone 12 Pro Max"))
.previewDisplayName("iPhone 12 Pro Max") 
}
}
}

struct Home: View {
@EnvironmentObject var tab: SelectedTab
@State var selectedTab = "Home"
init() {
UITabBar.appearance().isHidden = true
selectedTab = tab.getTab()
}
var body: some View{
NavigationView() {
ZStack(alignment: .bottom, content: {

TabView(selection: $selectedTab){
HomeTab()
NewsTab()
ProfileTab()
MoreTab()
}
}
}
}

}

您有:

struct Home: View {
@EnvironmentObject var tab: SelectedTab   // <--- here
....

对于TabBarContentView也是类似的。

这意味着你在你的父视图中,例如应用程序中,有这样的东西:

import SwiftUI
@main
struct MyApp: App {
@StateObject var tab = SelectedTab()   // <--- here
var body: some Scene {
WindowGroup {
Home().environmentObject(tab)  // <--- here
}
}
}  

如果你没有这样的东西,那么你就会得到你看到的错误。

Home中,tab初始化期间不可用。

struct Home: View {
@EnvironmentObject var tab: SelectedTab
@State var selectedTab = "Home"

init() {
UITabBar.appearance().isHidden = true
selectedTab = tab.getTab()  // tab is not available here.
}
------
}

有两种方法可以解决此问题。

1

更改home的签名。从TabBarContentView传递selectedTab

struct Home: View {
@EnvironmentObject var tab: SelectedTab

@State var selectedTab = "Home"

init(selectedTab: String) {
UITabBar.appearance().isHidden = true
self.selectedTab = selectedTab
}
---
}
struct TabBarContentView: View {
@EnvironmentObject var tab: SelectedTab

var body: some View {
Home(selectedTab: tab.getTab()).environmentObject(tab)
}
}

2

Home中使用@ObservedObject而不是@EnvironmentObject

struct Home: View {
@ObservedObject var tab: SelectedTab

@State var selectedTab = "Home"

init(tab: SelectedTab) {
UITabBar.appearance().isHidden = true
self.tab = tab
self.selectedTab = tab.getTab()
}
}

struct TabBarContentView: View {
@EnvironmentObject var tab: SelectedTab

var body: some View {
Home(tab: tab)
}
}

如果您不需要SelectedTab用于任何其他目的,请使用第二种方法。

相关内容

  • 没有找到相关文章

最新更新