【Swift】CollectionViewのページめくりアニメーション
完成図
↓1度目のスワイプ ↓2度目のスワイプ
解説
※注意点
・ページめくりを実装するには、
- Scroll DirectionをHorizontalに指定
- Scrolling - Horizontal Indicatorにチェック
- MidSpacingの値を0に指定
する必要がある。
↓
・今回はカスタムセルを使ってるが、何もいじってないので、使わなくてもOKかも。
・CollectionViewのsizeItemForAtをview.frame.width/heightにする
・ViewControllerを生成し、ConllecionViewで実装する
ストーリーボード
ソースコード
import UIKit class ViewController: UIViewController,UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { override func viewDidLoad() { super.viewDidLoad() collectionView.delegate = self collectionView.dataSource = self } @IBOutlet weak var collectionView: UICollectionView! { //カスタムセルをcollectionViewに登録 didSet { collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "cell") } } //ページに表示する色 let dataSource: [UIColor] = [.red, .green, .blue, .cyan, .yellow, .magenta] // MARK: - UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cv = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) //ViewControllerを生成 let viewController = UIViewController() //ViewControllerの位置とサイズを設定 viewController.view.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height) //ViewControllerの背景色を設定 viewController.view.backgroundColor = dataSource[indexPath.row] //collectionViewにViewControllerをセット cv.addSubview(viewController.view) return cv } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: view.frame.width, height: view.frame.height) } }