i want to show only 5 posts from my Wordpress Website into CollectionView in my Swift app. i am very new to Swift. i have set this as url
https://www.sikhnama.com/wp-json/wp/v2/posts/?categories=4&per_page=5
and this get only 5 posts from Wordpress but in collectionView after 5 posts it repeats the posts, but i want after 5 cells there should not be any more cell and post. this is my code ..
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return newsData.count (newsData.count/4)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if (indexPath.item % 4 == 3){
let adcell = collectionView.dequeueReusableCell(withReuseIdentifier: "adcell", for: indexPath) as! RelatedViewCell
adcell.banner.adUnitID = bannerAd
adcell.banner.rootViewController = self
adcell.banner.load(GADRequest())
adcell.banner.delegate = self
return adcell
}
else{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "postcell", for: indexPath) as! RelatedViewCell
cell.setup(with: newsData[indexPath.row-(indexPath.row/4)])
return cell
}
}
i have tried this also
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return 5
}
then i get error on this line that "Index out of Range"
cell.setup(with: newsData[indexPath.row-(indexPath.row/4)])
also tried
cell.setup(with: newsData[indexPath.row])
but not works,, help please
CodePudding user response:
As per comments...
With this code:
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
You are saying the collection view has two sections.
But, in neither numberOfItemsInSection
nor cellForItemAt
are you accounting for multiple sections.
So, you are duplicating the same cells in each section.
Unless you really have 2 sections, you should return 1
for numberOfSections
CodePudding user response:
The numbersOfItemsInSection func is what you will set to show only 5. But if you are grabbing data from an api there might not be 5 leaving you with a "Index out of Range" error.
What I would do:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
if newsData.count (newsData.count/4) > 5 {
return 5
} else {
return newsData.count (newsData.count/4)
}
}
This will check the data coming back and if greater than 5 only show 5 if it's less than 5 it will show that amount.