簡體   English   中英

SwiftUI - 內容瞬間出現,然后一起消失

[英]SwiftUI - Content appears from a split second then disappears all together

我正在從 FireStore 下載數據。 數據檢索完美。 我有數據,可以打印信息。 問題是,當我點擊文本/標簽以推送到預期視圖時,我使用.onAppear function 執行 function。 我的ObservableClass中的變量是@Published 我有數據,甚至可以根據檢索到的數據設置元素。 我正在使用 MVVM 方法,並且在我的項目中多次這樣做。 但是,這是我第一次遇到這個特殊問題。 我什至使用了在其他視圖中完全正常工作的函數,但是在這個特定的視圖中,這個問題仍然存在。 當我加載/推送此視圖時,數據會顯示一瞬間,然后視圖/畫布為空白。 除非元素是 static 即Text("Hello World")元素將消失。 我不明白為什么數據只是決定消失。

這是我的代碼:

struct ProfileFollowingView: View {
    @ObservedObject var profileViewModel = ProfileViewModel()
    var user: UserModel
    
    func loadFollowing() {
        self.profileViewModel.loadCurrentUserFollowing(userID: self.user.uid)
    }
    var body: some View {
            ZStack {
               Color(SYSTEM_BACKGROUND_COLOUR)
                   .edgesIgnoringSafeArea(.all)
                
                         VStack(alignment: .leading)  {
                             if !self.profileViewModel.isLoadingFollowing {
        
                                         ForEach(self.profileViewModel.following, id: \.uid) { user in
                                             VStack {
                                                Text(user.username).foregroundColor(.red)
                                                
                                             }
                                         }
                                         
                                         
                             }
                       
                             
                     
                         }
            } .onAppear(perform: {
                self.profileViewModel.loadCurrentUserFollowing(userID: self.user.uid)
            })
    }
}

這是我的loadFollowers function:

func loadCurrentUserFollowing(userID: String) {
    isLoadingFollowing = true
    API.User.loadUserFollowing(userID: userID) { (user) in
        self.following = user
        self.isLoadingFollowing = false
    }
}

我查看了檢索數據的代碼,它與我已經擁有的其他特性/功能完全一樣。 它只是發生在這個視圖上。

看起來API.User.loadUserFollowing(userID:)可能是異步的 - 可能在后台運行。 您需要更新主線程上的所有@Published變量:

func loadCurrentUserFollowing(userID: String) {
    isLoadingFollowing = true
    API.User.loadUserFollowing(userID: userID) { (user) in
        DispatchQueue.main.async {
            self.following = user
            self.isLoadingFollowing = false
        }
    }
}

您可能需要像這樣添加:“DispatchQueue.main.asyncAfter”

.onAppear {
       DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
             self.profileViewModel.loadCurrentUserFollowing(userID: self.user.uid) 
       }
 }

@ObservedObject更改為@StateObject

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM