0

I have searched and haven't seen a solution to:

  • I have a tableView that allows multiple selections
  • I want to have a button to allow those selections to all be cleared at the same time, in Swift. The button will be on a different viewController (a UIViewController) than the TableView. Is it ok to use protocol & delegate, or is singleton required? I want it to update when the button is clicked.

I saw an answer from Dejan Skledar a few years ago here: UITableViewCell checkmark to be toggled on and off when tapped and the function called resetChecks() seems what I was looking for, but I am having trouble getting what I wrote for Swift to work. When I run it, it doesn't actually go into the method, and then when the method is called, it crashes with "unexpectedly finding nil". Please, can anyone offer some advice? Thanks. Here is what I wrote:

func removeChecks() {
    for i in 0...grainTableView.numberOfSections - 1 {
        for j in 0...grainTableView.numberOfRows(inSection: i) - 1 {
            if let cell = tableView(grainTableView, cellForRowAt: [i,j]) as? UITableViewCell {
                cell.accessoryType == .none 
            }
        }
    }
}
Jayesh Thanki
  • 2,037
  • 2
  • 23
  • 32
Dawne
  • 11
  • 4
  • 1
    This is a very. very bad way. Don't call datasource and delegate methods like `tableView(_:cellForRowAt:` by yourself. The recommended way is to keep the `selected` state in the model. Then set this property to `false` in all instances and reload the table view. Your code even tries to change the invisible cells which is pretty inefficient. – vadian Jun 03 '18 at 17:35
  • Careful - there is not a single correct answer (despite all of the votes) in the question you linked. – rmaddy Jun 03 '18 at 18:00
  • I appreciate all suggestions, as I am learning and will improve with advice of those more knowledgeable. If you are willing to share some sample code to help me understand your point better, vadian I would appreciate it. Understanding how to call and use some of the code, especially for tableViews is challenging for me. – Dawne Jun 03 '18 at 23:59

1 Answers1

0

Send object from the preVC when you present the currentVC

class currentVC:UIViewController {

    var delegate:PreVC?

 func removeChecks() {

   if let grainTableView = delegate?.tableView {
      for i in 0...grainTableView.numberOfSections - 1 {
          for j in 0...grainTableView.numberOfRows(inSection: i) - 1 {
              if let cell = tableView(grainTableView, cellForRowAt: [i,j]) as? UITableViewCell {
                cell.accessoryType == .none 
             }
          }
      }
   }
}

//

func removeChecks() {

   if let grainTableView = delegate?.tableView {

      delegate?.shouldClear = true

      grainTableView.reloadData()

   }

}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87