Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
}
}
import UIKit
class CustomCell: UICollectionViewCell {
var label:UILabel!
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
//xibを使わない場合はこちらでセットアップ
setup()
}
func setup() {
label = UILabel(frame:self.contentView.frame)
label.textAlignment = .center
self.contentView.addSubview(label)
}
}
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//適当にコレクションビューを設置
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width:50,height:50)
let collectionView = CollectionView(frame: self.view.frame, collectionViewLayout: layout)
self.view.addSubview(collectionView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment