【问题标题】:Collection view index out of range when using refresher使用刷新时集合视图索引超出范围
【发布时间】:2023-03-24 16:26:01
【问题描述】:

我正在将一组图像加载到CollectionView

当我激活刷新器时,我正在调用这个方法:

func fetchPics(){
        //Clear array of post
        pics?.removeAll()

            Common.sharedInstance.fetchPics(completion: { (pics) in
            self.pics = pics
            self.collectionView?.reloadData()
            self.refresher.endRefreshing()
        })
    }

视图控制器的viewDidLoad 调用此方法,一切正常;但是,从复习者中调用它会给我一个:

fatal error: Index out of range

错误:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: postCellId, for: indexPath) as! PicCell

        //This is the line that gives me the error
        cell.pic = pics?[(indexPath as NSIndexPath).item]

        return cell
    }

在不出现此错误的情况下重新加载集合视图的适当方法是什么?

谢谢

【问题讨论】:

  • 试试cell.pic = pics?[indexPath.row] 看看是否有效

标签: ios arrays swift swift3 collectionview


【解决方案1】:

尝试将pics?.removeAll() 也放在完成块内,因为您的闭包代码将稍后执行,如果您的collectionView 可能被调用cellForItemAt indexPath,您将得到空数组。

 func fetchPics(){

    Common.sharedInstance.fetchPics(completion: { (pics) in

        pics?.removeAll()
        self.pics = pics
        self.collectionView?.reloadData()
        self.refresher.endRefreshing()
    })
}

注意:如果您不调用 removeAll,这也将起作用,因为您正在使用新值再次初始化数组。

【讨论】:

  • 我尝试在其中添加它,现在它附加到 pics 数组而不是重新加载它。就像它将内容添加到已经存在的内容中,就好像 remove all 甚至不存在一样。 @NiravD
  • @Walker 我说的是完成块而不是方法fetchPics,所以如果你从完成块中删除pics?.removeAll(),它仍然可以工作我没有告诉你fetchPics 方法再读一遍答案。
  • 我在 20 分钟前发布了答案。感谢您的帮助
【解决方案2】:

因为我调用了一个类的共享实例,我在其中进行了数据库调用。在那个类中,我创建了一个 pics 数组的实例,然后我通过完成块在其中返回。

我没有在 fetchPics 方法中调用 pics?.removeAll,所以它每次都附加到它上面。

感谢各位大佬的指导,得出这个答案

【讨论】:

    猜你喜欢
    • 2020-01-16
    • 1970-01-01
    • 2017-04-03
    • 2015-12-16
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多