2016-11-12 39 views
3

我讀了所有關於這個問題的相關帖子的插入行,但我仍然有一個錯誤:不能在表視圖

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

下面是代碼:

func appendItems(entities: [Entity]) { 
    if entities.count > 0 { 
     let entitesFirstPos = items.count 
     self.items.append(contentsOf: entities) 
     var indexPaths: [IndexPath] = [] 
     for i in entitesFirstPos..<items.count { 
      indexPaths.append(IndexPath(row: i, section: 0)) 
     } 

     self.tableView.beginUpdates() 
     self.tableView.insertRows(at: indexPaths, with: .none) 
     self.tableView.endUpdates() 
    } 
} 
+0

我覺得UITableView的委託方法是做這種事情的好地方。 – Vanya

+0

@Vanya什麼東西? –

+0

每次插入或刪除tableView中的行時,都應該更新數據源。檢查這個答案的更多細節:http://stackoverflow.com/a/40072874/1689376 – alexburtnik

回答

3

外貌像appendItems()是UITableViewController的子類中的函數。如果是這種情況,請嘗試以下操作。在不知道你的tableView(UITableView,numberOfRowsInSection:Int)和tableView(UITableView,cellForRowAt:IndexPath)是什麼樣子的情況下,不可能給出確切的答案。因此,這是基於self.items的假設就是一個包含數據的所有單元格在第0

首先儘量讓這種變化的數組:

//self.tableView.beginUpdates() 
//self.tableView.insertRows(at: indexPaths, with: .none) 
//self.tableView.endUpdates() 
self.tableView.reloadData() 

做出這樣的轉變將更新您的表格視圖不會將行插入動畫作爲所有新行的批處理。如果這樣的話你的問題就在appendItems()函數中。在這種情況下,儘量使這些更改:

func appendItems(entities: [Entity]) { 
    if entities.count > 0 { 
     self.tableView.beginUpdates() // <--- Insert this here 
     let entitesFirstPos = items.count 
     self.items.append(contentsOf: entities) 
     var indexPaths: [IndexPath] = [] 
     for i in entitesFirstPos..<items.count { 
      indexPaths.append(IndexPath(row: i, section: 0)) 
     } 

     //The following line is now at the top of the block. 
     //self.tableView.beginUpdates() 
     self.tableView.insertRows(at: indexPaths, with: .none) 
     self.tableView.endUpdates() 
    } 
} 

使這種變化將確保,如果行的部分數量是由UITableView中的調用beginUpdates()函數,甚至通過該功能之前查詢本身將返回正確的行數。在當前的設置中,假設self.items代表表視圖數據,更新的行數將在beginUpdates()被調用之前已經可見。如果這不起作用,則需要更多的代碼來查明問題。

+0

更改beginUpdates的位置適用於我。非常感謝! –