ios - 如何为 UITableView (Swift) 定义这个 numberOfRowsInSection

标签 ios swift uitableview

我的情况:我想在 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

        }
    }

最佳答案

  1. 声明一个变量 commentsForCurrentPost,它是一个 Post 类型的数组(与 allComments 类型相同):
    var commentsForCurrentPost: [Post] = []
  1. 当您检索所有评论时,您可以对其进行过滤并将其分配给 commentsForCurrentPost:
    commentsForCurrentPost = allComments.filter({ $0.text != nil && mirror.postID == $0.ogPost })
  1. 最后,这里是 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/

相关文章:

ios - 查找从哪个地区的应用商店下载 iOS 应用

ios - Swift Collection underestimateCount 使用情况

android - Android 和 Iphone 之间的应用感知蓝牙 BLE 通信

arrays - 如何使用实例变量访问另一个变量中的对象并返回

ios - 在 Swift 中渲染 MKPolyline

ios - 我想查看静态表格 View 中的所有单元格,这些单元格不会出现在故事​​板的屏幕上

iphone - iOS Facebook 登录但无法连接?

ios - 带有动态变量的 NSLocalizedString (Swift) - 不工作

swift - 搜索栏 textDidChange 错误

ios - UITapGesture 删除了在放弃键盘响应程序时从 UITableView 中进行选择的功能