右から左にスワイプすると、画面がスライドするようなアニメーションを実装するのが目的です。
UICollectionViewを使用したもので、下記のサイトを参考にしました。
↓
Qiita そのまま使える!iOSアプリを作るためのswiftサンプル集
上記の記事のサンプルコードを見ながら、模写したのですが、
・色が反映されない
・スライドしない
という問題に直面しています。
サンプルコードの方では動作するのでサンプルコードを1度全部コピペしましたが、ダメでした。
Swift4以上では、仕様が変わったのでしょうか?
エラーが1つも起こらないので、解決方法がわからず困っています。
どうかご指摘願います。
Swift
1import UIKit 2 3class ViewController: UIViewController,UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { 4 5 @IBOutlet weak var collectionView: UICollectionView! { 6 didSet { 7 collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "cell") 8 } 9 } 10 11 private let dataSource: [UIColor] = [.red, .green, .blue, .cyan, .yellow, .magenta] 12 13 // MARK: - UICollectionViewDataSource 14 15 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 16 return dataSource.count 17 } 18 19 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 20 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) 21 let viewController = UIViewController() 22 viewController.view.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height) 23 viewController.view.backgroundColor = dataSource[indexPath.row] 24 cell.addSubview(viewController.view) 25 return cell 26 } 27 28 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 29 return CGSize(width: view.frame.width, height: view.frame.height) 30 } 31} 32
Swift
1import UIKit 2 3class CollectionViewCell: UICollectionViewCell { 4 5 override func awakeFromNib() { 6 super.awakeFromNib() 7 // Initialization code 8 } 9 10}
※追記
Swift
1func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 2 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) 3 let viewController = UIViewController() 4 viewController.view.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height) 5// viewController.view.backgroundColor = dataSource[indexPath.row] 6 cell.contentView.backgroundColor = dataSource[indexPath.row] 7 cell.addSubview(viewController.view) 8 return cell 9 }
と書きましたが、変わりませんでした。
回答2件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。