-1

视频链接Youtube

控制台错误

Fatal error: No ObservableObject of type UserDefaultsConfig found. A View.environmentObject(_:) for UserDefaultsConfig may be missing as an ancestor of this view.: file SwiftUI, line 0

用户默认配置

class UserDefaultsConfig: ObservableObject {
    
    @Published var allFavoriteMovie: [PopularMovie] = []
    let defaults = UserDefaults.standard
    
    func setUserDefaults(value: PopularMovie) {
        let encoder = JSONEncoder()
        if let encoded = try? encoder.encode(value) {
            
            defaults.set(encoded, forKey: "favoriteMovie")
        }
        
        if let savedFavoriteMovie = defaults.object(forKey: "favoriteMovie") as? Data {
            let decoder = JSONDecoder()
            if let loadedFavMovie = try? decoder.decode(PopularMovie.self, from: savedFavoriteMovie) {
                allFavoriteMovie.append(loadedFavMovie)
                print("favMovie: \(allFavoriteMovie)")
            }
        }
    }
}

CustomTabView 首先打开

自定义选项卡视图

TabView(selection: $selectedTab) {
                
       MainView(searchMovie: SearchMovieVM(), mainVM: MainVM())
                .ignoresSafeArea()
                .tag(TabCategory.movieList)
                
       FavoriteView()
                .ignoresSafeArea()
                .tag(TabCategory.favorite)
            }

我在 MainView 中单击 MovieCell 并将其定向到 DetailView。

主视图

        NavigationLink(
            destination: DetailView(movie: .constant(mainVM.popularMovie[movie])),
            label: {
                MovieCell(popularMovie: .constant(mainVM.popularMovie[movie]))
                   .foregroundColor(Color(UIColor.label))
            })

详细视图

当我单击此处的按钮时,userDefaultsConfig 中的 setUserDefaults 函数正在运行。

struct DetailView: View {
    ....
    @StateObject var userDefaultsConfig = UserDefaultsConfig()
    var body: some View {
        ZStack {
            .....
            ScrollView(.vertical, showsIndicators: false) {
                .....
                    
                    HStack {
                        Spacer()
                        Button(action: { self.userDefaultsConfig.setUserDefaults(value: movie) }) {
                            Image(systemName: "suit.heart")
                                .imageScale(.large)
                                .foregroundColor(.red)
                        }
                    }
                    
                   ....
                    
                }
                .padding(.horizontal)
                
            }
        }
        .environmentObject(userDefaultsConfig)
    }
}

在 DetailView 页面的 UserDefaults 中保存的电影将显示在收藏夹页面上,但是当我打开收藏夹页面时,我收到错误消息。

收藏夹查看

struct FavoriteView: View {
    @EnvironmentObject var userDefaultsConfig: UserDefaultsConfig
    var body: some View {
        VStack {
//            ForEach(userDefaultsConfig.allFavoriteMovie, id: \.id) { item in
//                Text(item.title ?? "")
//            }
            Text("")
                .onAppear {
                    print(self.userDefaultsConfig.allFavoriteMovie)
                }
        }
    }
}
4

1 回答 1

0

您需要将状态对象放入CustomTabView,例如

struct CustomTabView: View {
    ....
    @StateObject var userDefaultsConfig = UserDefaultsConfig()

    ...

      TabView(selection: $selectedTab) {
                
          MainView(searchMovie: SearchMovieVM(), mainVM: MainVM())
                .ignoresSafeArea()
                .tag(TabCategory.movieList)
                
          FavoriteView()
                .ignoresSafeArea()
                .tag(TabCategory.favorite)
       }
       .environmentObject(userDefaultsConfig)    // << here !!
    ...

DetailView仅将其用作环境对象,就像您在 中所做的一样FavoriteView,即。

struct DetailView: View {
    @EnvironmentObject var userDefaultsConfig: UserDefaultsConfig

    ...
}
于 2021-04-07T18:38:27.023 回答