-1

I'm working on a UITableView that acts like checklist. I need to display checkmark when UITableViewCell tapped and hide the checkmark when UITableViewCell tapped again. I've tried this solution but I couldn't build because of var checked = [Bool]() part. How can I solve it with another way?

EDIT I've added the code below to cellForRowAtIndexPath

if checked == true {
            cell.accessoryType = .None
            checked = false
        } else if checked == false {
            cell.accessoryType = .Checkmark
            checked = true
        }
Community
  • 1
  • 1
do it better
  • 4,627
  • 6
  • 25
  • 41
  • you may need to store your rows' important details in your model, like e.g. _title_, _subtitle_, ..., and even the _checkState_ value. – holex Jan 17 '17 at 16:00

2 Answers2

4

I'm using this : (Swift 3)

    func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath)
    {
        if let cell = tableView.cellForRow(at: indexPath) {
            if self.selectedIndexPaths.contains(indexPath)
            {
                cell.accessoryType = .none
                self.selectedIndexPaths.remove(indexPath)
            }
            else
            {
                cell.accessoryType = .checkmark                    
                self.selectedIndexPaths.add(indexPath)
            }
            // anything else you wanna do every time a cell is tapped
        }    
    }
Jp4Real
  • 1,982
  • 4
  • 18
  • 33
1
  • Add a checked property of type Bool to your model.
  • In cellForRowAtIndexPath: set the checkmark according to the property.
  • When the cell is tapped toggle the property and reload the cell or table view.
vadian
  • 274,689
  • 30
  • 353
  • 361
  • I followed your instructions but in tableview cells came one checked and the other is checked and next one checked like +-+-+-+-+-+-. I've added the property as global and added the code that I've added in my post. – do it better Sep 26 '15 at 20:54
  • no, you have to add the `checked` property to the model which represents the data source of the table view to get individual values for each row. If you're using a dictionary add a key `checked` with an `Bool` value, if you're using a custom class (recommended), add a property. – vadian Sep 26 '15 at 21:03
  • I'm loading datas from an array. What do you mean by model? – do it better Sep 26 '15 at 21:07
  • The type of the items in the array is the model – vadian Sep 26 '15 at 21:08