2017-12-19 5 views
0

collectionView가 있습니다. 모든 셀에는 버튼 actionButton이 포함되어 있습니다. 버튼에 부착 된 타겟을 통해 버튼을 제거하려면 removeItem 메소드가 있어야합니다. datas에는 컬렉션 항목이 있습니다.컬렉션 셀 내의 버튼에서 인덱스가 잘못되었습니다. 삭제 셀 뒤의 셀

override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { 
     super.collectionView(collectionView, willDisplay: cell, forItemAt: indexPath) 
     guard let cell = cell as? ViewCell else { return } 
     let index = indexPath.row % datas.count 
     let item = datas[index] 
     cell.item = item 
     cell.actionButton.tag = indexPath.item 
     cell.actionButton.addTarget(self, action: #selector(removeItem), for: .touchUpInside) 
    } 

컬렉션보기에서 항목을 삭제하는 방법이 있습니다.

@objc func removeItem(sender: UIButton) { 
    let indexPath = IndexPath.init(item: sender.tag, section: 0) 
    self.datas.remove(at: indexPath.item) 
    collectionView?.deleteItems(at: [indexPath]) 
} 

그러나 컬렉션 셀에서 삭제 된 항목 버튼 인덱스는 다시로드되지 않습니다. 예를 들어, 인덱스가 [0, 0] 인 1 번째 항목을 다음 (2 번째) 항목으로 제거하면 1-st가되지만 버튼 인덱스는 여전히 [0, 1]입니다.

내가 뭘 잘못하고 왜 단추 인덱스가 다시 정렬되지 않습니다?

+1

콜렉션 뷰를 다시로드해야합니까? – AlexWoe89

+0

'collectionView? .deleteItems (at : [indexPath])'다음에'collectionView.reloadData()'를 추가하려고했으나 도움이되지 않았습니다. – andrey

+0

관련이 없지만'collectionView'는 선택 사항입니까? – rmaddy

답변

2

태그를 사용하여 콜렉션보기 또는 표보기에서 셀의 색인 경로를 추적하지 마십시오. 앞서 보았 듯이 셀을 삽입, 제거 또는 재정렬 할 수 있으면 실패합니다.

적절한 해결 방법은 컬렉션보기의 단추 위치를 기준으로 셀의 인덱스 경로를 가져 오는 것입니다.

@objc func removeItem(sender: UIButton) { 
    if let collectionView = collectionView { 
     let point = sender.convert(.zero, to: collectionView) 
     if let indexPath = collectionView.indexPathForItem(at: point) { 
      self.datas.remove(at: indexPath.item) 
      collectionView.deleteItems(at: [indexPath]) 
     } 
    } 
} 
+0

나는'let point = sender.convert (.zero, to : collectionView) '를'let point = collectionView? .convert (CGPoint.zero, from : 보낸 사람)'로 바꾸고 접근해야했는데 작동하지 않았다. . 나는 이유를 모른다. – andrey

+0

"작동하지 않음"을 정의하십시오. 적절한 포인트를 얻었습니까? 그럼 적절한'indexPath'를 얻습니까? 그리고 당신이 변경 한 라인은 어느 쪽이든 같은 결과를 주어야합니다. – rmaddy

+0

당신이 옳고 솔루션이 좋습니다. 내 문제는 뷰 계층에서 더 깊숙히 위치한 버튼을 누른 다음 기대했다. 버튼을 잡으려면'superview.superview'를보아야합니다. 여기 내 요점은'let point = collectionView.convert (sender.center, from : sender.superview? .superview)' – andrey