LoginSignup
0
1

More than 1 year has passed since last update.

CollectionViewまとめ(Swift)

Posted at

UICollectionViewとは

複数のデータ項目をカスタマイズして、綺麗にレイアウトできるもの

使い方

① UICollectionViewDelegate, UICollectionViewDataSourceのプロトコルを持ってくる

delgate.swift
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

...}

② viewdidiLoadの中で自分がつかう!ってことをしっかり宣言しておく

delegate2.swift
//delegateの宣言
  myCollectionView.delegate = self
//dataSourceの宣言
  myCollectionView.dataSource = self

③ あとはお好きにカスタマイズ!!

layout.swift
      //CollectionViewのレイアウトを初期化してあげる
        let layout = UICollectionViewFlowLayout()
        // Cell一つ一つの大きさをCGFloat型で指定
        layout.itemSize = CGSizeMake(30,30)
        // Cellのマージンを上下左右で設定
        layout.sectionInset = UIEdgeInsetsMake(10, 10, 20, 10)
        // セクション毎のヘッダーサイズをCGFloat型で指定
        layout.headerReferenceSize = CGSizeMake(50,15)
        // CollectionViewに上記で作ってきたデータを引数に入れてつくる
        myCollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
        // Cellに使われるクラスを登録(Id、今回はMyCell)
        myCollectionView.registerClass(CustomUICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")

④関数で実際に描画

kansu.swift
   //Cellが選択された際に呼び出される関数
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    }
    //Cellの総数を返す
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 100
    }
    //Cellに値を設定する
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
//さっき登録したMycellIDを型キャストして定数cellに入れてあげる
 let cell : UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", 
forIndexPath: indexPath) as! UICollectionViewCell
//背景色の変更
        cell.backgroundColor = UIColor.redColor()
//cellを返す。
        return cell

    }

まとめ

基本TableViewと使い方は変わらない 。両方の使用方法さえ理解できていれば幅広いデータのレイアウトの仕方ができそう。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1