2016-01-04 5 views
1

У меня есть массив, который заполняет вид таблицы - myPosts.удалить раздел в indexPath swift

Первая строка вида таблицы не является частью массива.

Каждая строка является его собственный раздел (с его собственным настраиваемым сноске)

Я пытаюсь выполнить удаление с помощью следующего кода:

func tableView(profileTableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { 
      if (editingStyle == UITableViewCellEditingStyle.Delete) { 
       myPosts?.removeAtIndex(indexPath.section - 1) 
       profileTableView.beginUpdates() 
       let indexSet = NSMutableIndexSet() 
       indexSet.addIndex(indexPath.section - 1) 
       profileTableView.deleteSections(indexSet, withRowAnimation: UITableViewRowAnimation.Automatic) 
       profileTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) 
       profileTableView.endUpdates() 
       ... 
       WS Call 
       ... 
      } 
} 

И журнал сообщает следующее:

'Invalid update: invalid number of rows in section 0. The number of rows contained in an 
    existing section after the update (1) must be equal to the number of rows contained in that 
section before the update (1), plus or minus the number of rows inserted or deleted from 
that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out 
of that section (0 moved in, 0 moved out).' 

Очевидно, проблема связана с перемещением 0, 0 перемещено, но я не понимаю, почему это так? или каким будет решение?

количество секций в Tableview выглядит следующим образом:

func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     if self.myPosts == nil 
     { 

      return 1 
     } 
     return self.myPosts!.count + 1 
    } 
+0

помните, что после удаления раздела с индексом 0 секция с индексом 1 станет новой секцией с индексом 0; поэтому вам нужно быть в курсе того, что в вашем _data-source_ (что мы ничего не знаем), и вам нужно что-то делать с строками. – holex

+0

@holex мой источник данных обновлен в вызове Webservice, который прокомментирован там. Что еще мне нужно делать с строками, отличными от deleteRowsAtIndexPath, который уже есть? – user2363025

+0

вы __must finish__ обновляете свой локальный _data-source_ до вызова метода '-endUpdates'; иначе вы обречены. – holex

ответ

4

Таким образом, ответ просто удалив строку, которая удаляет строки.

Так код здесь, чтобы удалить:

func tableView(profileTableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { 
     if (editingStyle == UITableViewCellEditingStyle.Delete) { 
      myPosts?.removeAtIndex(indexPath.section - 1) 
      profileTableView.beginUpdates() 
      let indexSet = NSMutableIndexSet() 
      indexSet.addIndex(indexPath.section - 1) 
      profileTableView.deleteSections(indexSet, withRowAnimation: UITableViewRowAnimation.Automatic) 
      // profileTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) 
      profileTableView.endUpdates() 
      ... 
      WS Call 
      ... 
     } 
    } 
1

Обновленный ответ на Swift 3.0 и сделал несколько дополнительных настроек:

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
    if editingStyle == .delete { 
     myPosts?.removeAtIndex(indexPath.section - 1) 
     let indexSet = IndexSet(arrayLiteral: indexPath.section) 
     profileTableView.deleteSections(indexSet, with: .automatic) 
     // Perform any follow up actions here 
    } 
} 

Использование beginUpdates() и endUpdates() не является необходимым , поскольку вы выполняете только одно действие, содержащее анимацию. Если вы делаете 2 или более, то стоит комбинировать их для получения жидкого эффекта.

Кроме того, это использует классы Swift 3, устраняя вызов NSMutableIndexSet(), для чего потребуется преобразование для работы с вызовом deleteSections().

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