0

I have a problem in a TableView. This is the class which contains the TableView.

class LogViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {
…
func loadLogList() – > [String] {
   …
}

The list contains all Logfiles in my Log file directory. In a custom TableViewCell I insert a button which deletes the Logfile. This is the user defined tableViewCell:

class LogTableViewCell: UITableViewCell {

…

    @IBAction func deletePressed(_ sender: Any) {
        let fileManager = FileManager.default
        do {
            try fileManager.removeItem(atPath: logURL!.path)
        }
        catch let error as NSError {
            print("Fehler: \(error)")
        }
    }

After pressing the button the dependent file will be removed. Now I want to refresh this list. But the Button is in the TableViewCell class and the function for refreshing the list is in the TableView class. How can I refresh the tableview and the corresponding array?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Jens
  • 45
  • 5

1 Answers1

0

You may use Notification Observer pattern for this, but you can access the tableView of the cell with this extension:

extension UITableViewCell {

    var tableView: UITableView? {
        return (next as? UITableView) ?? (parentViewController as? UITableViewController)?.tableView
    }
}

extension UIView {
    var parentViewController: UIViewController? {
        var parentResponder: UIResponder? = self
        while parentResponder != nil {
            parentResponder = parentResponder!.next
            if let viewController = parentResponder as? UIViewController {
                return viewController
            }
        }
        return nil
    }
}

- So now:

you can simply do tableView?.reloadData() inside the cell.

Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278