切换选项卡后,UI随ObservableObject更改 [英] UI changes with ObservableObject just after switching tabs

查看:45
本文介绍了切换选项卡后,UI随ObservableObject更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ObservableObject ,当服务器发送新数据时,我将使用它来更新我的UI(一个包含自定义结构数组的类).

I have a ObservableObject that I use to update my UI when new data is sent from the server (an a class which contains an array of custom structs).

由于某种原因,在发送数据时,将调用 ContentView body ,但数据不会更改.我什至添加了 print 语句来检查数组包含的数据是否正确.

For some reason, when the data is sent, the ContentView's body is called, but the data isn't changed. I even added a print statement to check if the data that the array contains is right and it is.

当我尝试切换到 TabView 上的另一个选项卡,然后再切换回主视图时,UI 确实得到更新.有人知道为什么我会在切换选项卡时立即更新UI,尽管在数据更改时会调用 body 来更新UI吗?

When I try to switch to another tab on my TabView, and then switch back to the main view, the UI does get updated. Does anybody know why the UI updates just when I switch tabs, although the body gets recalled to update the UI when the data changed?

HomeView

struct HomeView: View {
    @ObservedObject private var fbData = firebaseData

    var body: some View {
        TabView {
            //Home Tab
            NavigationView {
                ScrollView(showsIndicators: false) {
                    ForEach(self.fbData.posts.indices, id: \.self) { postIndex in
                        PostView(post: self.$fbData.posts[postIndex])
                            .listRowInsets(EdgeInsets())
                            .padding(.vertical, 5)
                    }
                }
                .navigationBarTitle("MyPhotoApp", displayMode: .inline)
                .navigationBarItems(leading:
                    Button(action: {
                        print("Camera btn pressed")
                    }, label: {
                        Image(systemName: "camera")
                            .font(.title)
                    })
                , trailing:
                    Button(action: {
                        print("Messages btn pressed")
                    }, label: {
                        Image(systemName: "paperplane")
                            .font(.title)
                    })
                )
            } . tabItem({
                Image(systemName: "house")
                    .font(.title)
            })

            Text("Search").tabItem {
                Image(systemName: "magnifyingglass")
                    .font(.title)
            }

            Text("Upload").tabItem {
                Image(systemName: "plus.app")
                    .font(.title)
            }

            Text("Activity").tabItem {
                Image(systemName: "heart")
                    .font(.title)
            }

            Text("Profile").tabItem {
                Image(systemName: "person")
                    .font(.title)
            }
        }
        .accentColor(.black)
        .edgesIgnoringSafeArea(.top)
    }
}

FirebaseData :

class FirebaseData : ObservableObject {
    @Published var posts = [Post]()

    let postsCollection = Firestore.firestore().collection("Posts")

    init() {
        self.fetchPosts()
    }

    //MARK: Fetch Data
    private func fetchPosts() {
        self.postsCollection.addSnapshotListener { (documentSnapshot, err) in
            if err != nil {
                print("Error fetching posts: \(err!.localizedDescription)")
                return
            } else {
                documentSnapshot!.documentChanges.forEach { diff in
                    if diff.type == .added {
                        let post = self.createPostFromDocument(document: diff.document)
                        self.posts.append(post)
                    } else if diff.type == .modified {
                        self.posts = self.posts.map { (post) -> Post in
                            if post.id == diff.document.documentID {
                                return self.createPostFromDocument(document: diff.document)
                            } else {
                                return post
                            }
                        }
                    } else if diff.type == .removed {
                        for index in self.posts.indices {
                            if self.posts[index].id == diff.document.documentID {
                                self.posts.remove(at: index)
                            }
                        }
                    }
                }
            }
        }
    }

推荐答案

我认为是SwiftUI错误.我这样解决这个问题.而不是渲染您的PostView(post:self.$ fbData.posts [postIndex])在ForEach内部实现发布视图.

I think is SwiftUI bug. I solve this problem like this. Instead of rendering your PostView(post: self.$fbData.posts[postIndex]) implement post view inside ForEach.

ForEach(self.fbData.posts.indices, id: \.self) { postIndex in
   Text(self.$fbData.posts[postIndex].comment)
   Text(self.$fbData.posts[postIndex].date)
   ....
}

这篇关于切换选项卡后,UI随ObservableObject更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆