我遇到了一个问题...我正在尝试在我的 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/