0

I am trying to create a cell with a 'count' variable which is a label that shows how many items are in a folder. I am doing this with a fetch request in the cellForRowAt func that counts the items in the request. The problem I am facing is that this isn't getting called every-time a new item is added resulting in the wrong count. Reloading the tableView every time in viewWillAppear fixes the problem but won't work in my use case as I am dealing with a lot of data. How could I fix this?

class FolderTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "folderCell", for: indexPath) as! FolderTableViewCell

        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Note")
        request.predicate = NSPredicate(format: "userDeleted = false")
        let count = try! context.count(for: request)


        let folders = folderNames(name: "TEST", icon: "TestImage", count: count)
        cell.updateFolders(with: folders)
        return cell
    }

}

class FolderTableViewCell: UITableViewCell {

    func updateFolders(with folders: folderNames) {
        folderCellLabel.text = folders.name
        folderCellImage.image =  UIImage(named: "TestImage")

        if folders.count != 0 {
            folderCellCount.text = "\(folders.count)"
        }
    }

}
mink23
  • 144
  • 1
  • 12

1 Answers1

2
tableView.reloadRows(at: [selectedIndex], with: .automatic)

selectedIndex is the index you want to reload.

refer to this: Is it possible to refresh a single UITableViewCell in a UITableView?

Thanks

Sailendra
  • 1,318
  • 14
  • 29
  • Is this the best way to go about doing this? The only problem with this method is that the deselection on unwind from another VC doesn't occur... – mink23 Nov 19 '19 at 03:07