ios - 在 CollectionView - Swift 中添加第二个自定义单元格

标签 ios swift uitableview uicollectionview

我遇到了一个问题...我正在尝试在我的 CollectionView 中添加一个新的自定义单元格以显示原生广告,基本上我是说每个

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

应该会出现与广告相关的单元格。现在的问题是,adsCell 正确显示,但它取代了其他内容。

因此,如果之前我有一个 collectionView,其中所有单元格都带有从 1 到 10 的标签,现在我有类似的东西:1、ADSCell、3,4、ADSCell,等等。

所以基本上它跳过了现在被 adsCell 替换的数字 2 和数字 5。

如何保留内容但在它们之间放置 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 语句 不是好习惯,最好让 dataSource 更通用,这样它可以包含广告项,比如你可以为每个dataSource项设置type来表示它是否有广告,那么你应该把广告项放到index 2和5 dataSource,然后在 cellForItemAt 中为每个项目检查该类型,如果它的广告返回 ADSCell,如果它没有返回您想要的单元格。

关于ios - 在 CollectionView - Swift 中添加第二个自定义单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57639680/

相关文章:

ios - 减少 objective-c 中静态库大小的最佳实践是什么?

ios - NSValue中的CGLayerRef - 何时调用retain()或release()?

ios - 选中行时防止 TableView 滚动

ios - 单击多行时如何使复选标记出现和消失?

ios - 苹果成员(member)中心登录错误

ios mapkit,运营商名称因 [LogMessageLogging] 崩溃 6.1 无法检索 CarrierName

ios - CocoaPods 中的 "` pod repo 更新 ` does not happen"错误

SwiftUI 发布的变量未更新

IOS Swift如何使用后台获取

swift - Swift-显示带有动画的标题