UICollectionViewCell をタップしたときにセルの色を変える

UICollectionView のセルをタップしたときに何のリアクションもないと寂しいので、セルの色を変える方法を調べました。

UICollectionViewDelegate を継承した Class に以下のメソッドを追加することで、セルをタップしている間は色を変え、離したら元の色に戻るという挙動になります。

    func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) {
        let cell = collectionView.cellForItemAtIndexPath(indexPath)!
        cell.backgroundColor = UIColor.clearColor() // タップしているときの色にする
    }

    func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath) {
        let cell = collectionView.cellForItemAtIndexPath(indexPath)!
        cell.backgroundColor = UIColor.darkGrayColor()  // 元の色にする
    }