视频链接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)
}
}
}
}
您需要将状态对象放置在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
...
}