i ma making Swift app with Xcode and using CollectionViewCell to fetch data from my WordPress Website. i have 2 cells in my CollectionView , one for loading posts and second for Google AdMob , I want to show Ads after 4 posts which is working great but now the problem is when Second cell is loaded i mean AdMob cell loaded then the post of that number is hidden behind it , like if there are posts of number 1,2,3,4,5 and ads load after 4 posts then number 5 post is no where.. this is my code
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if (indexPath.item % 5 == 1){
let adcell = collectionView.dequeueReusableCell(withReuseIdentifier: "adcell", for: indexPath) as! MovieCollectionViewCell
// Google Ads Here
return adcell
}
else{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MovieCollectionViewCell", for: indexPath) as! MovieCollectionViewCell
cell.setup(with: newsData[indexPath.row])
return cell
}
}
please help me to solve this , i want to load ads but when ad loaded the post of that number should be loaded in next item cell.. thanks
CodePudding user response:
First of all you use indexPath.item
in the if
block and indexPath.row
in the else
block, which might be a bit confusing but this is not the problem here.
indexPath.item
is 4 on your fifth cell, so the if
condition resolves to true
and you return the adcell
. On your sixth cell, indexPath.row
is now 5, so the fifth item of newsData
with index 4 is simply skipped.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if (indexPath.item % 5 == 4){
let adcell = collectionView.dequeueReusableCell(withReuseIdentifier: "adcell", for: indexPath) as! MovieCollectionViewCell
// Google Ads Here
return adcell
}
else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MovieCollectionViewCell", for: indexPath) as! MovieCollectionViewCell
cell.setup(with: newsData[indexPath.item-(indexPath.item/5])
return cell
}
}
EDIT:
If not already done:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return newsData.count (newsData.count/5)
}