見出し画像

Swiftで行こう!--CollectionView!(Section!)

CollectionViewの基本形は

です。それではSection分けしてみましょう!まず完成のイメージです。Sectionごとに色を分けています。

こんな感じになるようにコードを書いていきます。まずSectionを分けるコード

 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
 
       if section == 0 {
           return 7
       } else {
           return 2 
       }
   }

Section0は一列目で7個のセルを、Section1は二列目で2個のセルを配置するように。

次にSectionにより違う挙動にしたいので、とりあえず背景色を変化させてみましょう。

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
       
       switch(indexPath.section){         
       case 0:          
           cell.backgroundColor = .blue         
       case 1:         
           cell.backgroundColor = .red
       default:          
           print("section error")   
       }       
       return cell   
   }

この場合わけにより処理を分けて違うことをさせることができるようになりました。あとは綺麗に並べたいのでCollection Viewの設定を以下のように行います。

この設定をすることで上のSection一列目を7個、下のSection二列目の2個を間隔を開けて表示できるようになります。

最後にViewController全体のコードです。


この記事が気に入ったらサポートをしてみませんか?