Повторяющаяся галочка в табличном представлении

Я реализовал tableView с разделами и галочкой в ​​​​своем приложении. Я столкнулся с проблемой, когда я нажимаю на ячейку, галочка появляется на ячейке, но повторяется через 12 строк.

Я думаю, что проблема связана с моим разделом, функция «didSelectRowAtIndexPath» использует «indexPath.row» для идентификации ячейки, но, как и у меня есть некоторые разделы, мне также нужно указать «IndexPath.section», чтобы определить, какая ячейка какого раздела постучал.

Это мой код:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell!
    cell.textLabel?.text = objectsArray[indexPath.section].sectionObjects[indexPath.row]

return cell
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    //Je compte le nombre de ligne dans tableArray et créer autant de cellule que de ligne
    return objectsArray[section].sectionObjects.count
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return objectsArray.count
}

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
     return objectsArray[section].sectionName
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.deselectRowAtIndexPath(indexPath, animated: true)

    //On affiche le boutton pour sauvegarder les catégories
    SaveCategorie.hidden = false

    if let cell = tableView.cellForRowAtIndexPath(indexPath) {
        //Si la cellule est déja cochée
        if cell.accessoryType == .Checkmark
        {
            //je la décoche
            cell.accessoryType = .None 
        }
            else {
            cell.accessoryType = .Checkmark
            }
    }
}

Попытка сохранить элемент:

var selectedRowNumber: NSMutableIndexSet!

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell!
        cell.textLabel?.text = objectsArray[indexPath.section].sectionObjects[indexPath.row]

        cell.accessoryType = .None
        if let selectedRowNumber = self.selectedRowNumber {
            if indexPath.row == selectedRowNumber {
                cell.accessoryType = .Checkmark
            }
        }
        return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

        //On affiche le boutton pour sauvegarder les catégories
        SaveCategorie.hidden = false

        if let cell = tableView.cellForRowAtIndexPath(indexPath) {
            //Si la cellule est déja cochée


            cell.accessoryType = .Checkmark
            self.selectedRowNumber.addIndex(indexPath.row)

            dump(CatChoosen)
            dump(selectedRowNumber)
        }
    }

Но я получаю:

фатальная ошибка: неожиданно найдено nil при развертывании необязательного значения


person f1rstsurf    schedule 17.01.2016    source источник


Ответы (1)


TableViewCells используются повторно, поэтому вы снова видите это в 12-й строке, эта же ячейка была повторно использована.

Сохраните галочку для каждого элемента в ваших данных. Затем, когда ячейка загрузится, проверьте, установлен ли флаг, если да, установите галочку. Если нет, то Keep очищается.

person Chris    schedule 18.01.2016