2016-09-21 1 views
0

渡されたインデックスに基づいてすべての行に対して削除機能を実装しました。ios swift:セルの連続した削除後にUITableViewCellのタグが更新されない

各セルには、その行の削除を開始するボタンがあります。私は行を検出し、indexPathとdeleteRowAtIndexPaths(...)を使用する関数を削除するために渡すcell.tagを取る。

今、問題は、0番目の行を削除し続けると発生します。最初は、正しく削除されます。 0行目がなくなった。 1行目が0行目を置き換えます。 ここで、0行目をもう一度削除すると、現在の1行目が削除されます。

私が理解した理由は、cell.tagが更新されていないことです。 私は間違って何をしていますか? 問題に一貫性がありません。削除の間に待っていればOKです。私は別の行を削除する場合。他の行を削​​除し続けます。

どうすればいいですか?私はこれを既に検索し、適切な解決策やガイドを見つけることができませんでしたか?ここ

キーポイントは、セルを識別するためにcell.tagを使用しないでコード

+2

cell.tagが更新されているか、更新されていないと思われますか?問題の原因と思われるatleastコードを投稿してください。 – Santosh

+0

@Santosh今すぐご確認ください。これは主なコードです。しかし、あなたは理解するでしょう。十分でない場合は私に教えてください、私はさらにコードを追加します。 – mythicalcoder

+0

'deleteRowsAtIndexPaths'は' cellForRowAtIndexPath'を呼び出さないので、セルは更新されません。とにかく、indexPathをタグとしてセルに保持するのは良い方法ではありません。ビューではなくデータソースを更新します。 – vadian

答えて

0
// 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() 
} 

の主要部分です。むしろセルを直接使用してください。 commentのためにありがとうVadianありがとうございます。セルタグに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()を追加します。それは私のために働いた。

関連する問題