There is one table where the person’s data and check-mark are located. The data is displayed and the check-mark itself, only it is on the machine is turned on. When I press to turn it off - it is not pressed and does not turn off the check-mark. Here is my code

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() let user = users[indexPath.row] if let myName = user.name { cell.textLabel?.text = myName } cell.accessoryType = .checkmark return cell } 
  • one
    And how should it be turned off? You just show it in a cell. There must be logic that sets the behavior. - VAndrJ

1 answer 1

Add an array as a property of the controller

 var selectedIndex:[Int] = [] //тут будем хранить индексы выбранных строк //private var selectedIndex:[Int] = [] //или так, если нам не нужен доступ вне контроллера 

Change method

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() let user = users[indexPath.row] if let myName = user.name { cell.textLabel?.text = myName } if self.selectedIndex.contains(indexPath.row){ //проверяем есть ли такой елемент в нашем массиве cell.accessoryType = .checkmark } else { cell.accessoryType = .none } return cell } 

Add or change method

 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // тут проверяем если ячейка уже выбрана то удаляем из массива и убираем чекмарк // если не выбрана то добавляем в массив и ставим чекмарк if tableView.cellForRow(at: indexPath)?.accessoryType == .checkmark { self.selectedIndex.remove(at: self.selectedIndex.index(of: indexPath.row)!) tableView.cellForRow(at: indexPath)?.accessoryType = .none } else { self.selectedIndex.append(indexPath.row) tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark } tableView.deselectRow(at: indexPath, animated: false) //убираем выделение ячейки если не нужно обратное }