2016-09-21 3 views
0

전달 된 인덱스를 기반으로 모든 행에 대해 삭제 기능을 구현했습니다.ios swift : 셀의 연속 삭제 후 UITableViewCell의 태그가 업데이트되지 않습니다.

각 셀에는 해당 행에 대한 삭제를 시작하는 버튼이 있습니다. cell.tag를 사용하여 행을 감지하고 indexPath 및 deleteRowAtIndexPaths (...)를 사용하는 함수를 삭제합니다.

이제 0 번 행을 삭제할 때 문제가 발생합니다. 처음에는 올바르게 삭제됩니다. 0 번째 행이 없어졌습니다. 첫 번째 행이 0 번째 행을 대체합니다. 이제 다시 0 번째 행을 삭제하면 현재 1 번째 행이 삭제됩니다.

내가 이해 한 이유는 cell.tag가 업데이트되지 않는다는 것입니다. 정확히 내가 뭘 잘못하고 있니? 문제가 일관되지 않습니다. 삭제 사이에 기다리면 괜찮습니다. 한 행을 삭제하면. 다른 행을 계속 삭제합니다.

지금 어떻게해야합니까? 나는 이것을 이미 찾고 적절한 해결책이나 가이드를 찾을 수 없습니까? 여기

는 중요한 점은 셀을 식별 할 수 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가 업데이트되었거나 업데이트되지 않았다고 가정 할 수 있습니까? 문제의 원인이라고 생각하는 atleast 코드를 게시하십시오. – Santosh

+0

@Santosh 지금 확인하십시오. 이것은 코드의 주요 부분 일뿐입니다. 그러나 당신은 이해할 것입니다. 충분하지 않다면 알려주십시오. 코드를 더 추가하겠습니다. – mythicalcoder

+0

'deleteRowsAtIndexPaths'는'cellForRowAtIndexPath'를 호출하지 않으므로 셀은 업데이트되지 않습니다. 어쨌든 indexPath를 셀에 태그로 유지하는 것은 좋지 않습니다. 보기가 아닌 데이터 소스를 유지 보수하십시오. – vadian

답변

0

의 주요 부분이다. 직접 셀을 사용하십시오. 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()를 추가합니다. 그것은 나를 위해 일했다.

관련 문제