【问题标题】:How to display only 5 cells in CollectionView?如何在 CollectionView 中只显示 5 个单元格?
【发布时间】: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节...但是您的numberOfItemsInSectioncellForItemAt 都没有考虑到这一点。因此,您将在每个部分获得相同的数据。
  • 工作,谢谢 :D

标签: ios swift xcode uicollectionview uicollectionviewcell


【解决方案1】:

根据 cmets...

使用此代码:

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 2
}

您是说集合视图有两个部分。

但是,在numberOfItemsInSectioncellForItemAt 中,您都没有考虑多个部分。

因此,您在每个部分中复制了相同的单元格。

除非你真的有 2 个部分,否则你应该为 numberOfSections 返回 1

【讨论】:

    【解决方案2】:

    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 则将显示该数量。

    【讨论】:

      猜你喜欢
      • 2013-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      相关资源
      最近更新 更多