CollectionViewでセルを並べる

目標

  • ビューを生成
  • ビューにセルを表示
  • ビューのFlowLayoutを理解する
  • ビューのデリゲートメソッドとデータソースメソッドを理解する

ポイント

  • UICollectionViewFlowLayoutでセルの設定をする
  • データソースメソッド

・collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) ・func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int

・func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)

ソースコード

//デリゲートとデータソースクラスを継承する
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

//ビューを初期化
    var myCollectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        //layout セルのレイアウト設定に使用。セルの大きさやセルとセルの間の間隔を設定
        let layout = UICollectionViewFlowLayout()
        
        //ビューの生成
        myCollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
        
       //セルの大きさを設定
        layout.itemSize = CGSize(width: 50, height: 50)
        //セル間隔を調節
        layout.sectionInset = UIEdgeInsets(top: 16, left: 36, bottom: 32, right: 36)
        
       //列間隔の最小値を変更
        layout.minimumInteritemSpacing = 10
        //行間隔の最小値を変更
        layout.minimumLineSpacing = 10

        //ヘッダーのサイズを指定
        layout.headerReferenceSize = CGSize(width: self.view.frame.width, height: 100)
        //再利用するセルクラスをコレクションビューに登録する
        myCollectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
        
        //デリゲートとデータソースをクラスに反映
        myCollectionView.delegate = self
        myCollectionView.dataSource = self
    }

    //画面を更新するためのメソッド
    private func updateFrame() {
        
        self.myCollectionView.frame = self.view.frame
    }
    
    //セルがタップされた時に呼び出される
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        print("Num: \(indexPath.row)")
        print("Value:\((collectionView))")
    }
    
    //セル数を指定する
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 100
    }
    

    //各セルごとの設定を記述するメソッド
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath) as UICollectionViewCell
        cell.backgroundColor = UIColor.orangeColor()
        return cell
    }