2015-07-12 80 views
2

我想在表格视图控制器中删除一行动画。 我使用下面的代码:用动画删除表格行

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { 
    if (editingStyle == .Delete) { 

     tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) 

     let LM_ITEM = lebensmittel[indexPath.row] 
     managedObjectContext?.deleteObject(lebensmittel[indexPath.row]) 
     self.DatenAbrufen() 
    } 
} 

但按下Delete键后,我得到这个错误:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '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).'
*** First throw call stack:
(0x1856382d8 0x1973040e4 0x185638198 0x1864eced4 0x18a296e5c 0x10010e278 0x10010ef9c 0x18a2b0ea4 0x18a3a6880 0x18a0e5398 0x18a0ce474 0x18a0e4d34 0x18a0a3f54 0x18a0de82c 0x18a0ddee4 0x18a0b1120 0x18a3522b8 0x18a0af634 0x1855f0240 0x1855ef4e4 0x1855ed594 0x1855192d4 0x18ef6f6fc 0x18a116f40 0x100134420 0x1979aea08)
libc++abi.dylib: terminating with uncaught exception of type NSException

回答

4

你需要调用tableView.deleteRowsAtIndexPaths(..)

像在此之前更新您的模型,

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { 
    if (editingStyle == .Delete) { 

     let LM_ITEM = lebensmittel[indexPath.row] 
     managedObjectContext?.deleteObject(lebensmittel[indexPath.row]) 
     self.DatenAbrufen() 

     tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) 
    } 
} 
1

请尝试以下操作:

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { 
    if (editingStyle == .Delete) { 

     let LM_ITEM = lebensmittel[indexPath.row] 
     tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) 
     managedObjectContext?.deleteObject(LM_ITEM) 
     self.DatenAbrufen() 

    } 
}