How to define this numberOfRowsInSection for a UITableView (Swift)

Viewed 168

My situation: I want to show comments to a post in a UITableView, but they should only show u, if they belong to the post. I make this sure with mirror.postID == post.ogPost. This also works.

My problem: Since I return the count for all Comments, the TableView generates as many cells as there are Comments in my project in total. It only fills those that belong to the Post, but the other ones still get generated and stay empty. This isnt good.

The Solution?: I somehow would need to specify the count in numberOfRowsInSection, but I dont know how, that's why I ask you guys for help.

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

        }
    }
2 Answers
  1. Declare a variable commentsForCurrentPost which is an array of type Post (same type as allComments):
    var commentsForCurrentPost: [Post] = []
  1. When you retrieve all comments, you can filter it and assign it to commentsForCurrentPost:
    commentsForCurrentPost = allComments.filter({ $0.text != nil && mirror.postID == $0.ogPost })
  1. Finally, here are you tableView functions:
    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
}

You can use filter as following:

currentComments = allComments.filter({ $0.text != nil && mirror.postID == $0.ogPost })

And use that on tableviewDelegate

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return currentComments.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let post = currentComments[indexPath.row]
    let cell = tableView.dequeueReusableCell(withIdentifier: textComTableViewCell.identifier, for: indexPath) as! textComTableViewCell
    cell.configure(with: post)
    return cell
}
Related