4

私はFollowVCとFollowCell Setupをコレクションビューで持っています。次のコードを問題なく使用して、すべてのデータをuIcollectionビューのセルに正しく表示できます。私はまた、選択して「選択」モードでは、次のコードUItableviewCellすべて選択解除

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 

    if deletePressed == true { 
     let cell = collectionView.cellForItemAtIndexPath(indexPath) as! FollowCell 
     cell.checkImg.hidden = false 
    } else { 
     let post = posts[indexPath.row] 
     performSegueWithIdentifier(SEGUE_FOLLOW_TO_COMMENTVC, sender: post) 
    } 
} 

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) { 
    let cell = collectionView.cellForItemAtIndexPath(indexPath) as! FollowCell 
    cell.checkImg.hidden = true 
} 

使用して複数の画像を選択解除することができ

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 

    if let cell = collectionView.dequeueReusableCellWithReuseIdentifier("FollowCell", forIndexPath: indexPath) as? FollowCell { 

     let post = posts[indexPath.row] 

     cell.configureCell(post, img: img) 

     if cell.selected == true { 
      cell.checkImg.hidden = false 
     } else { 
      cell.checkImg.hidden = true 
     } 
     return cell 
    } 
} 

注、私は、各セルのselctionを行うことができますし、チェックマークが表示されます。セル上にしかし、私がやりたいことは、選択したすべてのセルを無効にしてcheckImgを削除するキャンセルボタンを持つことです。

私はプログラムがここで私は致命的なエラーを与えてクラッシュ

func clearSelection() { 
    print("ClearSelection posts.count = \(posts.count)") 

    for item in 0...posts.count - 1 { 
     let indexP = NSIndexPath(forItem: item, inSection: 0) 
     followCollectionView.deselectItemAtIndexPath(indexP, animated: true) 
     let cell = followCollectionView.cellForItemAtIndexPath(indexP) as! FollowCell 
     cell.checkImg.hidden = true 
    } 
} 

を試してみました:

let cell = followCollectionView.cellForItemAtIndexPath(indexP) as! FollowCell 

でオプションのエラーをアンラップしながら、意外なことに、私はそれがトラブルアンラップをしている理由を知らないnilを見つけ私のFollowCellには、checkImgのインスタンスが含まれています。私はdidSelectItemAtIndexPathのそれと似たような状況ですでにこれを使用していました。あなたが選択状態をクリアしているとき

おかげで、

答えて

9

ない選択したセルのすべての時点で、画面上にあってもよいので、collectionView.cellForItemAtIndexPath(indexPath)はnilを返すことがあります。フォースダウンキャストがあるので、この場合は例外が発生します。

あなたは潜在的なnil条件を処理するためのコードを変更する必要がありますが、あなたはまた、UICollectionView

let selectedItems = followCollectionView.indexPathsForSelectedItems 
for (indexPath in selectedItems) { 
    followCollectionView.deselectItemAtIndexPath(indexPath, animated:true) 
    if let cell = followCollectionView.cellForItemAtIndexPath(indexPath) as? FollowCell { 
     cell.checkImg.hidden = true 
    } 
} 
+0

感謝のindexPathsForSelectedItemsプロパティを使用して、あなたのコードをより効率的に行うことができます。私が必要としていることとまったく同じです。私は、しかし、すべてのreloadItemsコードを使用する必要はありません。私はあなたが言ったことをした、それはまさにあなたが言ったように働く。 – user172902

関連する問題