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

Posted

技术标签:

【中文标题】在 CollectionView 中添加第二个自定义单元格 - Swift【英文标题】:Add second custom cell in CollectionView - Swift 【发布时间】:2019-08-24 16:26:31 【问题描述】:

我遇到了一个问题...我正在尝试添加一个新的自定义单元格以在我的 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
    

【问题讨论】:

【参考方案1】:

cellForItemAt 函数中使用索引依赖if-statement 并不是一个好习惯,最好将dataSource 更通用化,以便它可以包含广告项,例如,您可以为每个@ 设置type 987654325@ items 表示它的广告与否,那么你应该把广告项目放在dataSource的索引2和5,然后在cellForItemAt中为每个项目检查那个类型,如果它的广告返回ADSCell,如果它没有返回你想要的单元格。

【讨论】:

【参考方案2】:

当 indexPath.row 等于 2 或 5 时,您正在使用 ADSCell,但在从数组中获取下一项时,您无需考虑这一点。

每次使用 ADSCell 时尝试添加一个偏移计数器,然后通过偏移调整常规单元分配。

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

您还需要考虑您的集合视图比数据源数组拥有更多的项目。

【讨论】:

你能说得更具体些吗?我应该如何以及在哪里处理“偏移” 在返回 adsCell 之前,您可以将偏移变量增加 1。正如上面@farhad 所说,这不是理想的解决方案。考虑更改数据源以适应不同的单元格类型。

以上是关于在 CollectionView 中添加第二个自定义单元格 - Swift的主要内容,如果未能解决你的问题,请参考以下文章

添加第二个 UINavigationController

ios:在点击collectionview单元格或tableview单元格时禁用第二个触摸事件

延迟加载 UICollectionViewCell 的自定义子视图

如何在 Swift 中复制/复制自定义 collectionview 单元格?

collectionview admob ios中的横幅广告

如何从collectionView中的第二项开始?