Table view representing more than one Swift 3 cell

I have a VERY annoying problem.

I have a tableView with more or less than 50 cells displaying some parameters that I can select the ones I want. I read in the Apple documentation that, by default, cells are reused when they are not displayed. In this case, if I select the first cell, every 6 cells 1 will be marked, that is, if I select the first 6 cells, ALL cells in the table will be marked!

There are several options in my table view. The selection is as follows:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.checkmark
}

How can i solve this? I know that you have such "prepareForReuse ()" for a subclass, will this be a solution? If so, can you give me an example of how you will do this?

+4
source share
3 answers

here is the code that can help you

var arr_selectedindePath = NSMutableArray()
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        if arr_selectedindePath .contains(indexPath) {

            arr_selectedindePath .remove(indexPath)
            tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.none
        }
        else
        {
          arr_selectedindePath .add(indexPath)
            tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.checkmark
        }

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

        let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")!
        if arr_selectedindePath .contains(indexPath) {
           cell.accessoryType = .checkmark
        }
        else
        {
          cell.accessoryType = .none
        }

    }
+3
source

You will need to update your data model accordingly, so that when you call cellForRowAtIndexPath, cells with updated content are displayed.

If you are not using a datamodel, you will need to store the indexPath in a mutable array and make a note about whether the current indexPath is marked or not.

Hope this helps.

+3
source

1.

protocol CellDelegate {

    func didTapOnButton(_ cell:Cell)

}

2.

var delegate:CellDelegate?

3.

override func prepareForReuse() {
        super.prepareForReuse()
        self.delegate = nil
    }


@IBAction func buttonTapped()
{
    self.delegate!.didTapOnButton(self)
}

tableview

1.

2.Inside cellForRowAtIndexPath cell.button

3.

 func didTapOnButton(_ cell: Cell) {
                print("off button clicked at index \(cell.button.tag)")

            }
-1
source

Source: https://habr.com/ru/post/1669368/


All Articles