LoginSignup
2
4

More than 5 years have passed since last update.

CollectionVIewで複数選択&tagの意外な使い方

Posted at

メモ

collectionViewの複数選択で調べていたら

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) 
{
         var cell = collectionView.cellForItemAtIndexPath(indexPath)
         if cell?.selected == true {
            cell?.backgroundColor = UIColor.orangeColor()
         }
          else 
             cell?.backgroundColor = UIColor.clearColor()
}

が見つかって早速実装したが、どうやらtapする度にtrue が入るのでどうにかfalseに切り替える必要があったが、変数でカウントする方法では関数が呼び出される度にカウントされてしまうため、cell独自のカウンターをtagを使ってつくってみた
生成のときに初期化してある

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        var cell = self.cellForItemAtIndexPath(indexPath)

        cell?.tag += 1
        if cell!.tag % 2 == 0 {
            cell?.selected = false
        }

        if cell?.selected == true {
            cell?.backgroundColor = UIColor.redColor()
        } else if cell?.selected == false {
            cell?.backgroundColor = UIColor.clearColor()
        }
    } 
2
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4