kujiraxo’s diary

日々の作業メモ。

Swiftで画像アプリ(その2)〜サムネ一覧画面

続けてサムネ一覧画面をUICollectionViewで作る。

まずは簡単な動作確認。下記のサイトを参考。

【Swift】UICollectionViewの使い方。自作セルでカスタマイズする。 | はじはじアプリ体験記

f:id:kujiraxo:20180708231924p:plain

class ViewController: UIViewController, UICollectionViewDataSource {

 

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

    }

 

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

 

    // データの個数を返す

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int)->Int{

        return 9    // とりあえず9個。

    }

    

    // データを返す

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)-> UICollectionViewCell

    {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "testCell", for: indexPath) as UICollectionViewCell

        

        cell.backgroundColor = UIColor.green    // とりあえず緑にして動作確認

        

        return cell

    }

 

}

動作のポイントは下記だった。

部品リストにあるコレクションビューをデバイス画面までドラッグ&ドロップで運ぶ(下図赤矢印)。Ctrlキーを押しながら部品をデバイス画面上の黄色い丸までドラッグ&ドロップで運ぶ(黄緑矢印)。

吹き出しで表示されたメニューから「dataSource」を選択する。これでコレクションビューに表示するデータをUIViewControllerクラスから貰う設定になった。

UIViewControllerクラス上にUICollectionViewクラスを乗っけたからこの設定が必要だったのかな?

 

MyPicApp-002