【问题标题】:When I return 1 in numberOfItemsInSection cellForItemAt not called in Swift当我在 numberOfItemsInSection 中返回 1 时,在 Swift 中未调用 cellForItemAt
【发布时间】:2020-05-28 10:16:52
【问题描述】:

我是 Swift 新手,我遇到了集合视图的问题。当我在 numberOfItemsInSection cellForItemAt 中返回 1 时不会调用,但是当我返回 2 时会调用。我无法理解问题。委托和协议也是正确的。

我的代码是这样的:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return arrSelectedSchoolIds.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = CollectionViewFilter.dequeueReusableCell(withReuseIdentifier: "SchoolLogo", for: indexPath as IndexPath) as! SchoolLogo
           cell.imgSchoolLogo.image = getSchoolLogo(schoolID: arrSelectedSchoolIds[indexPath.row])
           return cell
        }


func getSchoolLogo(schoolID:String?) -> UIImage
{
    switch schoolID
    {
    case "1":
        return UIImage(named: "image1")!
    case "2":
        return UIImage(named: "image2")!
    case "3":
        return UIImage(named: "image3")!
    case "4":
        return UIImage(named: "image4")!
    case "5":
        return UIImage(named: "image5")!
    case "6":
        return UIImage(named: "image6")!
    default:
        return UIImage(named: "defaultimage")!
    }
}

图像被添加到 Assest 文件中。

【问题讨论】:

  • 您可以尝试将“1”硬编码到您的“numberOfItemsInSection”,或者仔细检查该数组是否确实有一个对象?
  • @Yanchi 是的,我通过硬编码检查 1 个相同的问题
  • 无关,但从IndexPathIndexPath 的桥接是没有意义的。
  • 你能提供你的整个班级吗?
  • @vadian 意思是我不明白

标签: ios swift uicollectionview


【解决方案1】:

我遇到了同样的问题。当collectionView滚动方向为水平且collectionView的高度小于50时会发生这种情况。 我将collectionView的高度增加到50,问题就解决了。

【讨论】:

  • 这启发了我。不需要 50 的大小,但如果给定的大小不足以容纳内容,则单元格将不会呈现。谢谢。
【解决方案2】:

如果您不向集合视图提供内容大小信息,则不会调用 cellForItemAtIndexPath。如果您使用的是 Flow 布局,则需要正确设置项目大小。

【讨论】:

  • 你重写了这个委托方法吗?可选 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
【解决方案3】:

Swift 5.1

的解决方案

你可以尝试如下设置collection view的flowLayout:

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

【讨论】:

    【解决方案4】:

    我遇到了完全相同的问题。我的 UICollectionView 的高度为 16。我无法更改它。

    我最终伪造了第二个项目。如果我只有一件物品返回 2:

    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int

    在我的public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) 中,我正在查看是否超出范围,如果是,则返回相同的单元格,该单元格只是将自身呈现为空白。

    现在我的单个单元格显示得很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-08
      • 2021-07-04
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多