![](/img/trans.png)
[英]How to display particular section cells/items in centre horizontally in Collectionview Swift
[英]How to display only 5 cells in CollectionView?
我只想在我的 Swift 应用程序的 CollectionView 中显示来自我的 Wordpress 网站的 5 个帖子。 我是 Swift 的新手。我已将其设置为 url
https://www.sikhnama.com/wp-json/wp/v2/posts/?categories=4&per_page=5
这仅从 Wordpress 获得 5 个帖子,但在 5 个帖子后的 collectionView 中它重复了这些帖子,但我希望在 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])
但不起作用,请帮忙
根据评论...
使用此代码:
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
您是说集合视图有两个部分。
但是,在numberOfItemsInSection
和cellForItemAt
中,您都没有考虑多个部分。
因此,您在每个部分中复制了相同的单元格。
除非你真的有 2 个部分,否则你应该为numberOfSections
返回1
numbersOfItemsInSection 函数是您将设置为仅显示 5 的内容。但是,如果您从 api 中获取数据,则可能没有 5,从而导致“索引超出范围”错误。
我会做什么:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
if newsData.count + (newsData.count/4) > 5 {
return 5
} else {
return newsData.count + (newsData.count/4)
}
}
这将检查返回的数据,如果大于 5 则仅显示 5,如果小于 5 则将显示该数量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.