我是 Swift 的初学者,我根据一些教程粗略地尝试创建一个 MVVM 有点架构但是我发现具有一些 @Published 值属性的@ObservedObject 变量 wallpaperViewModel 并不能反映网络操作后的变化网络操作工作正常,我通过将接收到的值打印到控制台来确认它
这是所需的代码
壁纸视图模型
class WallpaperViewModel: ObservableObject {
@Published var wallpapers : [Wallpaper] = [Wallpaper]()
@Published var allBanners : [Banner] = [Banner]()
@Published var error: String = ""
//Handles error in requests, enum NetworkError has three cases unknown custom requestFailed
func errorHandler(error: NetworkError){
switch error {
case .custom(let customErr):
self.error = customErr
print(customErr)
case .requestFailed:
self.error = "Request Failed,Please check your internet connection"
print("Request Failed")
case .unknown:
self.error = "An unknown error occured"
print ("An unknown error occured")
case .networkNotConnected:
self.error = "Network not connected"
print ("Network not connected")
}
}
func getAllWallpapersfromApi (order: String, page: String){
NetworkingUtil().getAllWallpapers(orderBy: order, page: page){result in
switch result{
case .success(let wallpapers):
self.wallpapers = wallpapers
case .failure(let err):
self.errorHandler(error: err)
}
}
}
func getAllBanners(){
NetworkingUtil().getAllBanners(){result in
switch result{
case .success(let banners):
self.allBanners = banners
print("allBanners: (in VM)", banners)
case .failure(let error):
self.errorHandler(error: error)
}
}
}
}
这是我的主要观点
struct ContentView: View {
@ObservedObject var wallpaperViewModel = WallpaperViewModel()
@State private var selectedTab = 0
var body: some View {
VStack{
if(wallpaperViewModel.error.isEmpty){
TabView(selection: $selectedTab){
if(wallpaperViewModel.allBanners.count == 0){
Text("Loading..")
}
else{
ForEach(0..<wallpaperViewModel.allBanners.count){ bannerIndex in
//let banner = banners[bannerIndex]
Image("cover-cheetah")
.resizable()
.scaledToFill()
.frame(height:selectedTab == bannerIndex ? 230 : 180)
.cornerRadius(12)
}
}
}
.frame(height: 230)
.tabViewStyle(PageTabViewStyle())
.animation(.easeOut)
.padding(.horizontal)
}
else{
Text("\(wallpaperViewModel.error)")
}
}
.onAppear{
self.wallpaperViewModel.getAllBanners()
print("allBanners in ContentView",wallpaperViewModel.allBanners)
self.wallpaperViewModel.getAllWallpapersfromApi(order: "created", page: String(0))
print("allWallpapers in ContentView",wallpaperViewModel.wallpapers)
}
这是记录到控制台的值
这是模拟器上的输出