SwiftUI,UI不会根据viewModel的更改进行更新

时间:2020-10-02 11:44:54

标签: swift swiftui

我有一个带有@Published cardCampaigns属性的viewModel。在init()内部,我调用一个函数来修改cardCampaigns属性。尽管我使用主线程来更新属性,但由于某种原因该更改不会更新我的UI。当我打开屏幕时,在移到另一个选项卡并返回后,UI似乎卡住了,更新成功。有一个广告系列轮播,如果我按“详细信息”按钮,即使没有显示任何轮播,也可以正确打开包含相应广告系列的详细信息的屏幕。这是我的viewModel:

class CampaignsViewModel: ObservableObject {
    
    @Published var count: Int = 0
    var cardCampaigns: [CardCampaign] =  [CardCampaign]()
    @Published var isLoading: Bool = false

    
    init() {
        self.getCampaigns(completion: { suceedeed in
            print(suceedeed)
        })
    }
    
    func getCampaigns(completion: @escaping (Bool) -> Void) {
        self.isLoading = true
        NetworkEngine.shared.appNetwork.getCampaigns { result in
            DispatchQueue.main.async {
                self.cardCampaigns.removeAll()
            }
            self.isLoading = false
            switch result {
            case .success(let campaignsResult):
                if let campaignsList = campaignsResult {
                    DispatchQueue.main.async {
                        self.cardCampaigns = campaignsList.map { campaign in
                            return CardCampaign(campaign: campaign)
                        }
                    }
                }
                completion(true)
            case .failure(_):
                completion(false)
            }
        }
    }
}

和屏幕结构:

struct CampaignsView: View {
    
    @ObservedObject var viewModel: CampaignsViewModel = CampaignsViewModel()
    
    var body: some View {
        NavigationView {
            ZStack {
                VStack(spacing: 0) {
                    CustomNavigationBar(campaignsNumber: viewModel.cardCampaigns.count)
                        .padding([.leading, .trailing], 24)
                        .frame(height: 25)
                    CarouselView(count: $viewModel.count, cardCampaigns: $viewModel.cardCampaigns).frame(height: 240)
                    CampaignDescriptionView(idx: viewModel.count, cardCampaigns: viewModel.cardCampaigns)
                        .padding([.leading, .trailing], 24)
                    Spacer()
                }
                .onAppear {
                    if self.viewModel.cardCampaigns.count > 0 {
                        self.viewModel.cardCampaigns[0].show = true
                    }
                }
            }
            .padding(.top, 34)
            .background(Color.orBackgroundGrayColor.edgesIgnoringSafeArea(.all))
            .navigationBarHidden(true)
        }
    }
}

我错过了什么吗? 这是一张屏幕最初的外观照片: enter image description here

0 个答案:

没有答案