出来るもの
1-100の数字をCollectionViewに表示する
数字をタップすると数字に応じたアラートが出る
横にスクロール出来る
作成手順
・まずstoryboardに配置しているViewControllerをCollectionViewControllerに変更する
(もともとのViewControllerについてる矢印もこっちに付け替える。矢印は初期画面を指すので)
・cellのIdentifierも設定する。安直に”Cell”って名前を設定。
・cell内に数字を表示するためのラベルを設定
・tagも設定する。”1″で設定。
・ViewControllerが継承しているクラスをUICollectionViewControllerに変更
・コレクションに表示するデータ1-100を配列で用意
・セルの詳細なレイアウトを設定する
・セルのサイズ
・縦・横のスペースをどれくらいとるか
・スクロールを縦にするのか、横にするのか
・・など
class ViewController: UICollectionViewController { // コレクションに表示するデータ var items = [String]() override func viewDidLoad() { super.viewDidLoad() // セルの詳細なレイアウトを設定する let flowLayout : UICollectionViewFlowLayout = UICollectionViewFlowLayout() // セルのサイズ flowLayout.itemSize = CGSize(width: 100.0, height: 100.0) // 縦・横のスペース flowLayout.minimumLineSpacing = 10.0 flowLayout.minimumInteritemSpacing = 12.0 // スクロールの方向 flowLayout.scrollDirection = UICollectionView.ScrollDirection.horizontal // 上で設定した内容を反映させる self.collectionView.collectionViewLayout = flowLayout // 背景色を設定 self.collectionView?.backgroundColor = UIColor.lightGray // 配列を初期化(コレクションに表示するデータを作成) for i in 0 ..< 100 { items.append(String(i)) } }
・セクション(データをグルーピングしたもの)の数を決める。今回はセクションを分けるつもりはないので1固定
// セクションの数を決める override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 }
・セクション内のセルの数を決める。セルの数=データの数。なので、1-100のデータを詰めた配列の数を返す
// セクション内のセルの数を決める override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count }
・セルのデータを表示する
・ここが一番重要。
まず、これ。stroyboardのcellに設定したIdentifierをここで取得。ソース内で関連付ける
collectionView.dequeueReusableCell(withReuseIdentifier: “Cell”, for: indexPath)
・次にこれ。stroyboardのラベルに設定したタグを取得。ソース内で関連付ける
let label = cell.contentView.viewWithTag(1) as! UILabel
・IndexPath.rowに何番目の値かがわかるで、これをキーに配列からデータを取得
label.text = items[indexPath.row]
// セルのデータを表示 overrifde func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // セルを生成し、X番目に相当するデータを表示 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) cell.backgroundColor = UIColor.black let label = cell.contentView.viewWithTag(1) as! UILabel label.text = items[indexPath.row] label.textColor = UIColor.red return cell }
・セルが選択された時の処理を指定する
・今回は、アラートにしているが、遷移でもOK
・注意することは、セルに表示されているデータそのものが渡されるわけでない点。
セルに相当するIndexPathの値が渡されるだけなので、表示の時と同じように.rowで配列からデータを取得する
・アラートの表示方法については割愛
// セルが選択された時の処理を指定する override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let alert : UIAlertController = UIAlertController(title: "タイトル", message: "\(items[indexPath.row])", preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: nil) alert.addAction(okAction) present(alert, animated: true, completion: nil) }
Git
Gitにサンプルあげてます。
https://github.com/satoNobu/study_swift/commit/c25dad8cb51ef1c0ee44f996e7df278aea79e61c