导航链接在scrollview foreach中多次触发
我在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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论