0

I have a UITableViewController with custom UITableViewCell, and every cell has an UISwitch inside.

Need to update an information on my table (a string in the header), when any of these switches turn on/off (need to display the number of switches on in the section header).

I'm not confident with iOS and UIKit, but I've already found 2 possibile solutions:

  1. implement a delegate pattern between cell and table controller
  2. write update logic inside the function tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

In the first solution my TableViewController conforms to

protocol TableViewDelegate {
  func reloadTable()
}

that update its inner counter of switches on - and update the header section in function tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? - calling

DispatchQueue.main.async{
  self.tableView.reloadData()
}

Obviously my custom UITableViewCell has the reference to the delegate TableViewController and call its reloadTable().

The second solution instead is about the possibility to get the information of every cell in the method cellForRowAt indexPath. I've found that this function in not only called when the table has to be drawn, but also when I interact with a component into a cell.

So I need to implement a counting in the function cellForRowAt indexPath? Or the first solution with delegate pattern is a good one?

alecarnevale
  • 93
  • 1
  • 3
  • 7

2 Answers2

1

you should use a delegate in your cell.. can go like this

protocol CellDelegate: class {
   func actionDidPressed()
}

then in your cell should use it

class cell: UITableViewCell {
    weak var delegate: CellDelegate?

    @IBAction func buttonPressed() {
       delegate?.actionDidPressed()
    }

 }

then lastly in your controller you can conform to it

class ViewController: UIViewController {

     // in your cellAtIndexPath method after creating cell you can 

     cell.delegate = self 

}

I prefer to make an extension to the View Controller to conform to delegates

extension ViewController: CellDelegate {
  func actionDidPressed() {
      // add the action you need here 
   }
}
Mohamed Emad Hegab
  • 2,665
  • 6
  • 39
  • 64
  • Ok, this is exactly my first solution (my favorite). And it works. I was looking for a confirm, or an alternative good way. Thanks for your advice. – alecarnevale Mar 31 '19 at 21:39
  • Like @Shunzhe said.. NSNotification is also a way.. but i would not use it in such situation cause you'll have to make sure you removed the observer from each cell after end using it.. it's a big tricky and can be a pitfall.. plus the code will be smelly after a while – Mohamed Emad Hegab Apr 01 '19 at 06:33
0

You can use NSNotification to pass data between different views. You'll need to register the recipient controller by using the addObserver method and use post to send a message. You can refer to this post