【发布时间】:2021-07-25 11:35:23
【问题描述】:
我正在尝试从 JSON 文件中计算每个帖子有多少 cmets。
post 和 cmets 通过 id 链接。每个帖子都有一个id,每个评论都有一个帖子if来区分它属于哪个帖子。
我已经显示了所有帖子,我想在帖子上显示一个标签,显示特定帖子的 cmets 数量。
到目前为止,我已经设法为帖子上的每个评论显示一个文本块,因此我可以通过计算文本块重复的次数来查看逻辑是否正常以及每个帖子有多少 cmets,但这不是什么我想要,我只想显示一个带有数字的文本块。
这是我目前所拥有的: 上面写着“here to show its working”的文字就在那里,所以你可以看到它正在工作并将被删除(我也知道因为它在 foreach 循环内,它会根据有多少 cmets 一遍又一遍地显示有)
所以我的问题是我如何以某种方式计算这些 cmets 并显示一个数字?:
var body: some View {
ZStack {
HStack {
VStack(alignment: .leading) {
Text(post.title)
.foregroundColor(.white)
.font(.system(size: 22, weight: .medium, design: .rounded))
ForEach(comments) { comment in
if comment.postId == post.id {
Text("here to show its working")
.foregroundColor(.pink)
.font(.system(size: 16, weight: .light, design: .rounded))
}
}
Text("comments")
.foregroundColor(.pink)
.font(.system(size: 16, weight: .light, design: .rounded))
}.padding()
Spacer()
}
}//: VStack
.onAppear {
commentApi().getComments { (comments) in
self.comments = comments
}
}
.background(
LinearGradient(gradient: Gradient(
colors: [
Color.purple, Color.blue
]),
startPoint: .topLeading,
endPoint: .bottomTrailing
)
)
.shadow(color: .black.opacity(0.1), radius: 15, x: 0, y: 0)
.cornerRadius(15)
}//: Body
这就是它的样子:
这就是我希望它的外观和工作方式(我只是硬编码“5 cmets”来显示我想要实现的目标):
【问题讨论】:
-
我建议不要尝试解决视图中与模型相关的每个方面。相反,将您的模型和视图分开。然后,视图只呈现
count,因为它只是模型中的另一个属性。然后问题归结为从原始模型中获取每个帖子的 cmets 数量并将其添加到新模型中 - 这是一个单一的衬里。