2017-12-19 23 views
0

私はcollectionViewを持っています。すべてのセルにはボタンactionButtonが含まれています。ボタンは添付されたターゲットを介して削除する方法removeItemを持っています。私は配列を持っていますdatasはコレクションのためのアイテムを含んでいます。collectionView内のボタンのインデックスが間違っています。削除後のセルcell

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番目になりましたが、ボタンインデックスは[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

関連する問題