Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reloading tableview data from custom cell

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?

like image 830
SwiftStudier Avatar asked Aug 31 '15 18:08

SwiftStudier


1 Answers

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

like image 85
IamMashed Avatar answered Oct 29 '22 08:10

IamMashed