我的情况:我想在 UITableView 中显示对帖子的评论,但如果它们属于帖子,它们应该只显示你。我使用 mirror.postID == post.ogPost
来确保这一点。这也有效。
我的问题:因为我返回了所有评论的计数,所以 TableView 生成的单元格数量与我的项目中的评论总数一样多。它只填充属于 Post 的那些,但其他的仍然生成并保持为空。这不好。
解决方案?我不知何故需要在 numberOfRowsInSection
中指定计数,但我不知道该怎么做,这就是我向你们寻求帮助的原因。
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allComments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let post = allComments[indexPath.row]
if post.text != nil && mirror.postID == post.ogPost{
let cell = tableView.dequeueReusableCell(withIdentifier: textComTableViewCell.identifier, for: indexPath) as! textComTableViewCell
cell.configure(with: post)
return cell
}
return UITableViewCell() // default: return empty cell
}
}
最佳答案
- 声明一个变量 commentsForCurrentPost,它是一个 Post 类型的数组(与 allComments 类型相同):
var commentsForCurrentPost: [Post] = []
- 当您检索所有评论时,您可以对其进行过滤并将其分配给 commentsForCurrentPost:
commentsForCurrentPost = allComments.filter({ $0.text != nil && mirror.postID == $0.ogPost })
- 最后,这里是 tableView 函数:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return commentsForCurrentPost.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let post = commentsForCurrentPost[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: textComTableViewCell.identifier, for: indexPath) as! textComTableViewCell
cell.configure(with: post)
return cell
}
关于ios - 如何为 UITableView (Swift) 定义这个 numberOfRowsInSection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62366797/