facebook twitter hatena line google mixi email

Ios/swift/CollectionView

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

CollectionViewControllerとは

画像リストなどを作成できるUIController

3列画像表示のサンプル

-storyboard

  1. UICollectionViewControllerのオブジェクトをstoryboardへドラッグ
  2. class名を"ThumbListViewController"へ
  3. storyboardIdを"ThumbListViewControllerId"へ
  4. minSpacing(画像間の距離)を行・列ともに10から0へ

-ThumbListViewController.swift

import UIKit
class ThumbListViewController: UIViewController ,UICollectionViewDataSource, UICollectionViewDelegate {
   private var _imgs: [String] = []
   override func viewDidLoad() {
       super.viewDidLoad()
   }
   func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
       let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CustomCell", forIndexPath: indexPath) as! CustomThumbCollectionViewCell
       let img: String = _imgs[indexPath.row]
       cell.setCell(img)
       return cell
   }
   func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       return _imgs.count
   }
   // 画像の大きさを端末幅の1/3へ
   func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
       let width: CGFloat = view.frame.width / 3 - 2
       let height: CGFloat = width
       return CGSize(width: width, height: height)
   }
   // Cell が選択された場合
   func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
       let id: Int! = _imgs[indexPath.row].id
       if id != nil {
           let img: String = _imgs[indexPath.row]
       }
   }
   override func didReceiveMemoryWarning() {
       super.didReceiveMemoryWarning()
   }
}

-CustomThumbCollectionViewCell.swift

class CustomThumbCollectionViewCell: UICollectionViewCell {
   @IBOutlet weak var customImageView: UIImageView!
   func setCell(imgpath: String) {
       customImageView.image = UIImage(named:imgpath)
       customImageView.clipsToBounds = true // はみ出た部分をトリム
   }
}