【问题标题】:CollectionView method cellForItemAt indexPath: not being called (Swift)CollectionView 方法 cellForItemAt indexPath: 未被调用 (Swift)
【发布时间】:2020-02-04 12:00:20
【问题描述】:

我使用了UICollectionViewController,我正在尝试将图像添加到我的收藏视图单元格,但UICollectionView 方法未被调用。

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

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! CircularCollectionViewCell
        cell.imageName = images[indexPath.row]
        return cell

    }

【问题讨论】:

  • 行数是多少?您何时填充了images 数组?如果需要,你yourCollectionView.reloadData() 了吗?在主线程中?它真的是 UICollectionViewController 还是 UIViewController 添加了 UICollectionView?如果那是一个添加的 UICollectionView,它的框架是什么?
  • @KishanBhatiya 我用过collectionVC。我需要遵守委托和数据源吗?
  • 您使用 Assets (xcassets) 还是手动文件夹:您是如何将图像添加到项目中的?
  • @Larme 我的images 数组正在填充,但cellForItemAt 方法仍未被调用。我使用了一个手动文件夹,并将其作为带有蓝色图标的参考文件夹。
  • 如果你使用 UICollectionViewController,数据源已经设置好了。我以为images 是空的,不是这样吗?完成后致电reloadData()?

标签: ios swift xcode uicollectionview


【解决方案1】:

提示:CellforRow at:indexPath 方法如果在重新加载之前更改了 collectionView 的大小或位置,则不会调用,请确保您没有这样做。

【讨论】:

  • 我如何检查这个?
  • 您更改任何其他约束可能会间接影响collectionview的大小或位置,因此只需尝试调用collectionView.layoutIfneeded()方法并强制在主线程中重新加载collectionView。
  • 你的意思是我应该打电话给layoutifneeded()viewdidload?
  • 在UICollectionViewController 中不应该这样。我不认为它以奇怪的大小模态呈现。
【解决方案2】:
self.collectionView.reloadData()

【讨论】:

    【解决方案3】:

    在UICollectionViewController 子类delegate 和dataSource 中默认设置。

    并且默认情况下在数据源方法中使用0。您需要更改这些值。

    override func numberOfSections(in collectionView: UICollectionView) -> Int {        
        return 1
    }    
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {        
        print(images.count)
        return images.count
    }
    

    【讨论】:

    • 我已经做到了。这将打印图像的计数。这是 14。
    • @FarazA.Khan 仍然没有调用cellForItemAt? cellForItemAt 方法中有断点吗?
    • 显然我已经设置了断点。仍然没有被调用。
    【解决方案4】:

    如果您不向集合视图提供内容大小信息,cellForItemAtIndexPath 将不会被调用。

    您可以设置collectionViewLayout,如下所示:

     let flowLayout = UICollectionViewFlowLayout()
     flowLayout.scrollDirection = .vertical
     collectionView.collectionViewLayout = flowLayout
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      • 1970-01-01
      相关资源
      最近更新 更多