2016-01-17 3 views
0

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

Я думаю, что проблема возникает из моего раздела, функция «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) 
     } 
    } 

Но я получаю:

fatal error: unexpectedly found nil while unwrapping an Optional value

ответ

0

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

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

+0

Спасибо за вашу помощь, я обновил свой пост! – f1rstsurf

+0

Хорошо, мне это удалось, спасибо! – f1rstsurf

Смежные вопросы