2017-06-02 11 views
0

私はを持っています。カスタムセルを使用するUICollectionViewControllerがあります。選択されたセルを区別するために、ユーザーがセルをタップすると呼び出され、セルの背景色を緑に変更する関数があります。 問題は、ユーザーが別のセルをタップすると、前のセルが選択されていないこと、別の関数が呼び出されることです。 collectionViewがスクロールされない限り、それは正常に動作しますが、ユーザーがcollectionViewをスクロールして、選択されたものが画面の表示矩形から外れると、私の選択解除機能が機能せず、緑色の背景を持つ2つのセルがあります。UICollectionViewの不可視セルが選択されたままになっています

それはデモです:

enter image description here

あなたは上部の緑色の背景を持つセル、および最後にもう一つがある見ることができます。ここで

は、セルを選択し、選択解除する方法は、次のとおりです

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 

    if let cell = collectionView.cellForItem(at: indexPath) as? CategoryCollectionViewCell { 
      cell.selectItem() 
    } 
} 

override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { 
    for _cell in collectionView.visibleCells { 
     if let __cell = _cell as? CategoryCollectionViewCell { 
      __cell.deselectItem() 
     } 
    } 

    if let indexPath = collectionView.indexPathsForSelectedItems { 
     if indexPath.count > 0 { 
      if let _cell = collectionView.cellForItem(at: indexPath.first!) as? CategoryCollectionViewCell { 
       _cell.deselectItem() 
      } 
     } 
    } 

    return true 
} 
+0

で試してみてください? – KKRocks

+0

@KKRocksいいえ、ユーザーは1つのセルのみを選択する必要があります。 – Maysam

+0

ok try my answer – KKRocks

答えて

0

私は推測する、私が選択した別のセルを選択し、再利用可能なセルのためになることを意味し、単にこれは、スクロールビューをスクロールした後に起こる、あなたの問題を得ました自動的に選択されるようになりましたが、これは一般的な問題であり、主にUITableViewとUIScrollViewで発生します。

if conditiondatasourceに、そのdelegateelseの部分に使用した場合、このビューでは問題が解決されます。例えば

if let indexPath = collectionView.indexPathsForSelectedItems { 
     if indexPath.count > 0 { 
      if let _cell = collectionView.cellForItem(at: indexPath.first!) as? CategoryCollectionViewCell { 
       _cell.deselectItem() 
      } 
     } 
     else{ 
     // do something here 
     } 
    } 
    else{ 
     // do something here 
    } 

が、これはあなたを助けることを願っています。

0

が、このことは、複数の選択

let selectedIndexPath : IndexPath 
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
     if let cell = collectionView.cellForItem(at: indexPath) as? CategoryCollectionViewCell { 
      cell.selectItem() 
     } 

     if let preViousSelectedcell = collectionView.cellForItem(at: selectedIndexPath) as? CategoryCollectionViewCell { 
      preViousSelectedcell.deselectItem() 
     } 
     selectedIndexPath = indexPath 

    } 
+0

それは同じです。それでも、古いものが選択されています。 – Maysam

+0

このアプローチが正しい場合は、正しい前のセルがあることを確認する必要があります。 – KKRocks

関連する問題