2017-04-19 34 views
0

我有一個UITableViewCellBEMCheckBox,我想刪除時沒有自來水在這裏按下電池是我的代碼:從的tableView刪除單元格內的UITableViewCell

func didTap(_ checkBox: BEMCheckBox) { 
    let index = tableView?.indexPath(for: self) 
    MenuViewController().products.removeObject(forKey: "Product\(index!.row)") // removes the cell from the database of the tableview 
    tableView?.deleteRows(at: [index!], with: .fade) 
} 

,這裏是我如何得到tableView

extension UIView { 
    func parentView<T: UIView>(of type: T.Type) -> T? { 
     guard let view = self.superview else { 
      return nil 
     } 
     return (view as? T) ?? view.parentView(of: T.self) 
    } 
} 

extension UITableViewCell { 
    var tableView: UITableView? { 
     return self.parentView(of: UITableView.self) 
    } 
} 

我得到follwing錯誤:

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 (2) must be equal to the number of rows contained in that section before the update (2), 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

'MenuViewController()products.removeObject(forKey: 「產品\(指數.row)」)'那是創造了一個全新的'MenuViewController'對象?你能檢查對象是否被正確刪除? – Larme

回答

0

它與您的數據源相關。您的數據源不會相應更新。您應該在重新加載UITableview之前檢查您的數據源。這是由於數據項計數不匹配造成的。

0

你需要通知你將要修改的項數表視圖:

tableView?.beginUpdates() 
// Perform the item and cell removal 
tableView?.endUpdates() 

始終確保插入/刪除數據源相同數量的項目作爲細胞的數量你的桌子視圖。

您可以檢查decoumentation here

+0

不,在這種情況下,您不需要'begin-/endUpdates'。仔細閱讀文檔* ...如果您希望後續**插入** s **,刪除和選擇操作** s ** ... *複數,這意味着**多個**操作。對於單個操作,根本不需要。 – vadian

相關問題