完成形はこちら

機能説明
- 横にスライドするUICollectionViewのCellをタップすると色が
UIColor.systemTeal
に変わります。
コードと簡単説明
-
collectionViewを横にスライドできるようにするには、
UICollectionViewFlowLayout()のインスタンス.scrollDirection = .horizontal
を設定します。 -
今回は、UICollectionViewのCellをタッチした時の処理を追加しています。その為には、
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {}
を使用します。
ViewController
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
let collectionViewFlowLayout = UICollectionViewFlowLayout() //インスタンス作成
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
collectionViewFlowLayout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
collectionViewFlowLayout.scrollDirection = .horizontal //ここで、横にスクロールに変更してます
collectionView.collectionViewLayout = collectionViewFlowLayout
}
}
extension ViewController: UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.size.width / 4 - 10, height: collectionView.frame.size.width / 4 - 10)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let selectCell = collectionView.cellForItem(at: indexPath)!
selectCell.backgroundColor = UIColor.systemTeal
}
}
終わり
最近、長くなったif文を短く出来ないか、考えるのが楽しくて楽しくて。
ご指摘、ご質問などありましたら、コメントまでお願い致します。