且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

UICollectionView中的多个部分

更新时间:2023-02-05 11:38:55

确保分配数据源&委托给CollectionView

Make sure assigning DataSource & Delegate to CollectionView

1.使用以下方法给出要显示的部分数量

1.Give number of sections you wanna show using below method

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 2
}

2.使用以下方法为CollectionView设置每个部分的项目计数.

2.Set item count of each sections for CollectionView using below method.

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
   return (section == 0) ? list.count : list2.count
}

3.将每个项目的单元格分配给CollectionView.

3.Assigning cell for each item to CollectionView.

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

    //If you are using multiple cells based on section make condition 

     if indexPath.section == 0 {
             //make sure the identifier of your cell for first section
             let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell1", for: indexPath)
            // do your stuffs
             return cell
     }else{
             //make sure the identifier of your cell for second section
             let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell2", for: indexPath)
            // do your stuffs
             return cell
      }

}