【发布时间】:2022-12-10 14:01:16
【问题描述】:
我只想在我的 Swift 应用程序中将我的 Wordpress 网站上的 5 个帖子显示到 CollectionView 中。我对斯威夫特很陌生。我已将此设置为网址
https://www.sikhnama.com/wp-json/wp/v2/posts/?categories=4&per_page=5
这只从 Wordpress 获得了 5 个帖子,但是在 collectionView 中,在 5 个帖子之后它重复了这些帖子,但我希望在 5 个单元格之后不应该有更多的单元格和帖子。 这是我的代码..
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
}
}
我也试过这个
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return 5
}
然后我在“索引超出范围”这一行得到错误
cell.setup(with: newsData[indexPath.row-(indexPath.row/4)])
也试过
cell.setup(with: newsData[indexPath.row])
但不起作用,请帮忙
【问题讨论】:
-
你回来了2节...但是您的
numberOfItemsInSection和cellForItemAt都没有考虑到这一点。因此,您将在每个部分获得相同的数据。 -
工作,谢谢 :D
标签: ios swift xcode uicollectionview uicollectionviewcell