Reloading tableview data from custom cell

SwiftStudier picture SwiftStudier · Aug 31, 2015 · Viewed 9k times · Source

I have a tableView with custom cell.

I also have a .swift-file for this custrom cell.

In this file I have a function which doesn't have a sender:AnyObject in entering parameters.

How can I call tableView.reloadData() from this function?

Answer

IamMashed picture IamMashed · Aug 31, 2015

try to create a delegate. (which I would assume you know about, if not take a look in apple documentation about the delegate and protocols)

So the idea i would suggest is to create a function that will be implemented in your UITableViewController (or a UIViewController conforming to UITableViewDelegate protocol)

Firstly try to add a protocol on top of your CustomCell.swift file.

protocol CustomCellUpdater: class { // the name of the protocol you can put any
    func updateTableView()
} 

then inside your CustomCell.swift:

weak var delegate: CustomCellUpdater?

func yourFunctionWhichDoesNotHaveASender () {
    ...
    delegate?.updateTableView()
}

after that in your UITableViewController (or equivalent)

func updateTableView() {
    tableView.reloadData() // you do have an outlet of tableView I assume
}

Lastly make your UITableview class conform to the CustomCellUpdater protocol

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

   let cell = tableView.dequeueReusableCell(withIdentifier: "yourIdentifier", for: indexPath) as! YourTableViewCell
   cell.delegate = self
}

In theory it should work. Let me know if I am missing anything