如何在集合视图中显示广告

我正在尝试在我的collectionView中随机添加一些横幅广告。

每个collectionView单元格将是一个基本的图像(在这里黑色的方块使事情变得更容易)从一个数组dynamic填充(假设这是一个非常长的数组,并称之为“longDataArray”),我会从网上获得。

我可以设法添加一些横幅广告到我的collectionView,但问题是,它打破了我的longDataArray的顺序。 例如,为了testing在indexPath 6添加广告横幅的时间,广告横幅正确地显示在indexPath 6,我能够pipe理单元格的宽度变化, 但是 indexPath对应的图像6我的longDataArray显然永远不会出现。

我也可以把我的longDataArray分成两部分,然后使用部分:section 0 = firstPartOfArray,section 1 = ad banner,section 2 = secondPartOfArray。 但是,这需要很大的努力来创build不同的数组和节,只是添加一个广告横幅,显然不是我正在寻找的。

所以我的问题是,你如何在你的collectionView中添加横幅广告(只有一个部分),但保持indexPath逻辑?

我search了很多关于这个的内容,并且很惊讶我不能为这个问题提出任何解决scheme。

你们有什么想法吗?

谢谢!

截图

所以我的问题是,你如何在你的collectionView中添加横幅广告(只有一个部分),但保持indexPath逻辑?

您只需调整索引path即可考虑广告。 例如,假设您希望每个第15个单元格包含一个广告。 我们在这里使用基于1的算术来使math直观。 细胞1-14只会得到他们的常规内容,细胞15会有一个广告,细胞16-29将获得项目15-28的内容,细胞30将获得另一个广告,等等。 因此,您的-collectionView:cellForItemAtIndexPath:方法需要确定索引path是指广告单元(在这种情况下,基于1的项目编号可以被15整除)或内容单元(每隔一个单元格)。 在后一种情况下,还需要调整项目号以获得正确的内容。

 NSInteger item = indexPath.item + 1; // switch to 1-based numbering if (item % 15 == 0) { // we have an ad cell, so return a cell configured with an ad } else { item = item - (item / 15); // subtract the ad cells item -= 1; // switch back to 0-based indexes // return a cell configured with the data at index `item` } 

您还必须在处理单元格的其他方法中进行相应的计算,例如-collectionView:numberOfItemsInSection: 出于这个原因,编写一些可以进行调整的实用方法可能是一个好主意。

对于UICollectionView你必须有两个自定义的UICollectionView

  1. Imageview用于Imageview
  2. Cell2用于横幅广告。

cellForItem

 if (indexPath.item == 6){ // dequeue your cell2 here return cell2 } else{ // dequeue your cell1 here return cell1 } 

实现UICollection查看委托stream布局并像这样使用

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{ if (indexPath.item == 6){ return CGSizeMake(60,60) } else{ return CGSizeMake([[UIScreen mainScreen] bounds].size.width, 60.0) } } 

要在您的应用中展示广告,请使用AdMob