簡體   English   中英

當我在 numberOfItemsInSection 中返回 1 時,在 Swift 中未調用 cellForItemAt

[英]When I return 1 in numberOfItemsInSection cellForItemAt not called in Swift

我是 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 文件中。

如果您不向集合視圖提供內容大小信息,則不會調用 cellForItemAtIndexPath。 如果您使用的是 Flow 布局,則需要正確設置項目大小。

Swift 5.1解決方案

您可以嘗試設置collection view的flowLayout,如下所示:

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

我有同樣的問題。 當collectionView滾動方向為水平並且collectionView的高度小於50時發生這種情況。我將collectionView高度增加到50,問題解決了。

我遇到了完全相同的問題。 我的 UICollectionView 的高度為 16。我無法更改它。

我最終偽造了第二個項目。 如果我只有一件物品返回 2:

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

在我的public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)中,我正在查看我是否超出范圍,如果是,則返回相同的單元格,該單元格只是將自身呈現為空白。

現在我的單個單元格顯示得很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM