导航链接在scrollview foreach中多次触发

发布于 2025-02-06 07:39:23 字数 1463 浏览 2 评论 0原文

我在foreach的内部有一个导航链接,这使导航链接被多次调用。我已经尝试了许多解决方案。

例如,将导航链接移到foreach循环外。但是,这与动画混为一谈:

此解决方案:在这里查看。但是,我不太了解它,也无法使其完全奏效。也许你们中的一个人可以重写它,因此在我的情况下这很有意义。

我为任何解决方案开放

struct MainVIewPostView: View {
    @ObservedObject var postRowViewModel: PostRowViewModel
    
  var body: some View {
        ScrollView {
          ForEach(postViewModel.posts, id: \.id) { post in <- There are 4 post
                ...
        
                NavigationLink {
                        CommentView(post: postRowViewModel.post)
                    } label: {
                        Image(systemName: "message")
                            .font(.system(size: 26))
                            .foregroundColor(.black)
                        
                        Text("24")
                            .foregroundColor(.black)
                    }
            }
        }
    }
}

struct CommentView: View {
    @ObservedObject private var commentViewModel: CommentViewModel
    
    
    init(post: Post) {
        commentViewModel = CommentViewModel(post: post)
        print("in") <- This gets called 4 times, as many times as there are post. I only want it to get called 1 time
    }
 }

I have a NavigationLink inside of a ForEach, which makes the NavigationLink gets called multiple times. I have tried many solutions to this.

For E.g. moving the NavigationLink outside the ForEach loop. However, this messes with the animation: Look Here

I also tried following this solution: Look Here. However, I didn't understand it quite well, and couldn't make it work completely. Maybe one of you guys can rewrite it, so it makes sense in my case.

I'm open for any solutions

struct MainVIewPostView: View {
    @ObservedObject var postRowViewModel: PostRowViewModel
    
  var body: some View {
        ScrollView {
          ForEach(postViewModel.posts, id: \.id) { post in <- There are 4 post
                ...
        
                NavigationLink {
                        CommentView(post: postRowViewModel.post)
                    } label: {
                        Image(systemName: "message")
                            .font(.system(size: 26))
                            .foregroundColor(.black)
                        
                        Text("24")
                            .foregroundColor(.black)
                    }
            }
        }
    }
}

struct CommentView: View {
    @ObservedObject private var commentViewModel: CommentViewModel
    
    
    init(post: Post) {
        commentViewModel = CommentViewModel(post: post)
        print("in") <- This gets called 4 times, as many times as there are post. I only want it to get called 1 time
    }
 }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文