简体   繁体   中英

Add second custom cell in CollectionView - Swift

I'm facing out a problem... I'm trying to add a new custom cell for show native ads in my CollectionView and basically I'm saying that every

indexPath.row == 2 || indexPath.row == 5

there should appear the cell related to the ads. The problem now is, the adsCell is correctly appearing but it took place of the other content.

So if before I was having a collectionView with all the cell with a label with written from 1 to 10, now I have something like: 1, ADSCell, 3,4, ADSCell, and so on.

So basically it's skipping the number 2 that now is replaced by the adsCell and also the number 5.

How can I keep the content but place between them the adsCell?

  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0 {
            return itemsViewModel.itemsModel.featuredItems.value.count
        }else {
            return itemsViewModel.itemsModel.dailyItems.value.count
        }

    }

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

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


        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "itemCell", for: indexPath) as! DailyItemCollectionViewCell

        let cellAds = collectionView.dequeueReusableCell(withReuseIdentifier: "adsCell", for: indexPath)

        if indexPath.section == 0{

            if indexPath.row == 2 || indexPath.row == 5 {
                return cellAds
            }else {
                print("INDEX", indexPath)
                let featuredItems = itemsViewModel.itemsModel.featuredItems.value[indexPath.row]
                cell.configure(with: featuredItems)
            }
        }else {
            let dailyItems = itemsViewModel.itemsModel.dailyItems.value[indexPath.row]
            cell.configure(with: dailyItems)
        }

        return cell
    }

cellForItemAt函数中具有依赖于索引的if-statement不是一个好习惯,最好让dataSource更笼统,以便它可以包含广告项,例如,您可以为每个dataSource项设置type以表明其广告,那么您应该将广告项目放置在dataSource索引2和5上,然后在cellForItemAt为每个项目检查类型,如果其广告未返回所需的单元格,则返回ADSCell。

When indexPath.row equals 2 or 5 you are using the ADSCell, but you then don't account for this when getting the next item from the array.

Try adding an offset counter for every time ADSCell is used then adjust the regular cell assignments by the offset.

let featuredItems = itemsViewModel.itemsModel.featuredItems.value[indexPath.row-offset]

You'll also need to account for your collection view having more items than the data source array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM