初歩的な手順です。実装の方法が人によってまちまちで、適当に実装したら何かが足らずにCollection Viewが出ないみたいなことがあったので、備忘録のために残しておきます。不親切な記事で世のため人のためにならず、すみません。
手順
1, storyboardにCollectionView配置
2, CollectionViewCellにIdentifierを定義
3, クラスにUICollectionViewDelegate
UICollectionViewDataSource
を継承
4, @IBOutlet weak var myCollectionView: UICollectionView!
みたいにしてソースコードからUIを操作できるようにする
5, データの実装
//データの個数を返すメソッド
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return 30
}
//データを返すメソッド
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
//コレクションビューから識別子「TestCell」のセルを取得する。
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TestCell", for: indexPath as IndexPath) as UICollectionViewCell
//セルの背景色をランダムに設定する。
cell.backgroundColor = UIColor(red: CGFloat(drand48()),
green: CGFloat(drand48()),
blue: CGFloat(drand48()),
alpha: 1.0)
return cell
}