1

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
    }
 }
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • Place NavigationLink outside of ScrollView and activate it programmatically, like here https://stackoverflow.com/a/64559054/12299030. – Asperi Jun 10 '22 at 05:00
  • @Asperi This triggers a bug with the View: https://www.youtube.com/shorts/Tj1h7OAs08s. I still haven't found a solution to this. – Alexander Rubino Jun 10 '22 at 09:10
  • May not be related, but you did not put the scroll view contents in a list and VStack. – Ptit Xav Jun 10 '22 at 10:37

0 Answers0