[swift] CollectionViewの実装

サンプルコード

class collectionViewController: UIViewController,UICollectionViewDataSource, UICollectionViewDelegate , UICollectionViewDelegateFlowLayout{

let array = ["1","2","3","4"]

override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView.delegate = self
        collectionView.dataSource = self
}

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{

        //Cellというidentiferに予めStoryBoardで設定しておく
        let cell:UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
        let row = indexPath.row
        
        //タグ1のアイテムを取得
        let contentView = cell.contentView.viewWithTag(1) as! UIImageView
        contentView.image = UIImage(named:"image.png")

        //タグ2のアイテムを取得
        let label = cell.contentView.viewWithTag(2) as! UILabel
        label.text = String(array[row])
        
        return cell
    }
    
    //セルのサイズ コードでは高さ75、横幅は画面半分の-12で調整している
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        let cellHeight:CGFloat = 75.00
        let cellWidth:CGFloat = self.view.frame.size.width/2-12
        return CGSizeMake(cellWidth, cellHeight)
    }
 
    //セルの間隔指定  
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
        return UIEdgeInsetsMake(5, 7, 5, 7)
    }
    
    //セクション数
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    // 要素数を入れる、要素以上の数字を入れると表示でエラーとなる
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return array.count;
    }
    
    //タップされた時の挙動
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let row = indexPath.row
        //その他メソッド
        
    }
}

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です