|
import UIKit |
|
|
|
|
|
class CheckCollectionView: UICollectionView { |
|
|
|
let reuseID = "cell" |
|
|
|
let checkColor = UIColor.blue //チェックしたもののみ色をつける |
|
let defaultColor = UIColor.white |
|
|
|
//からの配列を用意 |
|
var checkArray:[IndexPath] = [] |
|
|
|
required init?(coder aDecoder: NSCoder) { |
|
super.init(coder: aDecoder) |
|
} |
|
|
|
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { |
|
super.init(frame: frame, collectionViewLayout: layout) |
|
self.delegate = self |
|
self.dataSource = self |
|
self.register(CustomCell.self, forCellWithReuseIdentifier: reuseID) |
|
} |
|
|
|
} |
|
|
|
extension CheckCollectionView: UICollectionViewDelegate { |
|
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { |
|
guard let cell:CustomCell = collectionView.cellForItem(at: indexPath) as? CustomCell else { return } |
|
|
|
//位置を探す |
|
if let index = checkArray.index(where: { (index) -> Bool in |
|
return index == indexPath |
|
}){ |
|
//見つかったら配列から削除する |
|
checkArray.remove(at: index) |
|
cell.contentView.backgroundColor = defaultColor //セルの色をデフォルトに戻す |
|
}else { |
|
//配列内にないので追加する |
|
checkArray.append(indexPath) |
|
cell.contentView.backgroundColor = checkColor //背景に色をつける |
|
} |
|
} |
|
} |
|
|
|
extension CheckCollectionView: UICollectionViewDataSource { |
|
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { |
|
return 100 |
|
} |
|
|
|
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { |
|
let cell:CustomCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseID, for: indexPath) as! CustomCell |
|
|
|
cell.label.text = String(indexPath.row) //適当に行番号を表示しておく |
|
|
|
//チェックされているかどうかで色を分岐 |
|
if checkArray.contains(indexPath) { |
|
cell.contentView.backgroundColor = checkColor |
|
}else { |
|
cell.contentView.backgroundColor = defaultColor |
|
} |
|
|
|
return cell |
|
} |
|
} |