2016-09-21 23 views
0

我已根據傳遞的索引爲任何行實現了刪除功能。ios swift:在連續刪除單元格後,UITableViewCell的標記未更新

每個單元都有一個按鈕來啓動該行的刪除操作。我使用cell.tag來檢測該行,並通過刪除使用indexPath和deleteRowAtIndexPaths(...)的函數。

現在,問題發生在我繼續刪除第0行時。最初,它會正確刪除。第0行不見了。第一排替換第0排。 現在,如果我再次刪除第0行,它將刪除當前的第1行。

我明白的原因是cell.tag沒有更新。 我究竟做錯了什麼? 問題不一致。如果我在刪除之間等待,那就沒問題。如果我連續刪除一行。它不斷刪除其他行。

我現在該怎麼辦?我已經搜索了這個,無法找到合適的解決方案或指導?

這裏是代碼

// Typical code having Programmatic UITableView 
// ... 

func addTestEvent(cell: MyCell) { 
    func onSomeAction() { 
     dispatch_async(dispatch_get_main_queue(), { 
      self.removeRow(cell.tag) 
     }) 
    } 

    ... 
    // onSomeAction() called on click on the button 
} 


func test(cell: MyCell) ->() { 
    ... 
    addTestEvent(cell) 

} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier(NSStringFromClass(MyCell), forIndexPath: indexPath) as! MyCell 
    cell.tag = indexPath.row 
    cell.test = { (cell) in self.test(cell) } 
    return cell 
} 


func removeRow(row: Int) { 
    let indexPath = NSIndexPath(forItem: row, inSection: 0) 
    tableView.beginUpdates() 
    posts.removeAtIndex(row) 
    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) 
    tableView.endUpdates() 
} 
+2

我們怎樣才能假設你的cell.tag已更新或未更新?發佈您的代碼至少你認爲是造成這個問題。 – Santosh

+0

@Santosh請立即確認。這只是代碼的主要部分。但你會明白。讓我知道如果不夠,我會添加更多的代碼。 – mythicalcoder

+0

'deleteRowsAtIndexPaths'不會調用'cellForRowAtIndexPath',因此單元格不會更新。無論如何,將indexPath作爲標記保存在單元格中並不好。維護數據源,而不是視圖。 – vadian

回答

0

主件關鍵的一點是不要用cell.tag識別細胞。而是直接使用這個單元格。感謝Vadiancomment。將indexPath保存在單元標籤中並不是一個好習慣。現在我知道爲什麼了!

這個答案給了我解決問題的主要提示。 https://stackoverflow.com/a/29920564/2369867

// Modified pieces of code. Rest of the code remain the same. 

func addTestEvent(cell: MyCell) { 
    func onSomeAction() { 
     dispatch_async(dispatch_get_main_queue(), { 
      self.removeRow(cell) 
     }) 
    } 
    // ... 
    // onSomeAction() called on click on the button 
} 

func removeRow(cell: UITableViewCell) { 
    let indexPath = tableView.indexPathForRowAtPoint(cell.center)! 
    let rowIndex = indexPath.row 
    // ... 
} 
0

刪除單元格後添加tableView.reloadData()。這對我有效。

相關問題