在运行时设置numberOfItemsInSection - UICollectionView

时间:2015-09-12 00:45:09

标签: ios swift uicollectionview

我想在运行时设置collectionView的numberOfItemsInSection。我会经常在运行时以编程方式更改值,并且想知道如何。

我有一个要在我的UICollectionView中显示的图像数组(每个UICollectionViewCell有1个图像),用户可以更改要显示的图像的类别,这也将改变要显示的图像数量。加载视图时,numberOfItemsInSection设置为allClothingStickers数组的计数。但这个数字太高了。确实显示的数组是clothesStickersToDisplay数组,它是allClothingStickers数组的一个子集。

滚动后出现此错误:

  

致命错误:数组索引超出范围

这是因为项目数量变小了,但UICollectionView numberOfItemsInSection属性没有变为较小的数字。

我有这个函数在运行时设置UICollectionView中的单元格数。

func collectionView(collectionView: UICollectionView,
    numberOfItemsInSection section: Int) -> Int {
        return self.numberOfItems
}

此函数用于设置stickersToDisplay数组(我想在此处更新numberOfItemsInSection属性):

func setStickersToDisplay(category: String) {
        clothingStickersToDisplay.removeAll()
        for item in self.allClothingStickers {
            let itemCategory = item.object["category"] as! String
            if itemCategory == category {
                clothingStickersToDisplay.append(item)
            }
        }
        self.numberOfItems = clothingStickersToDisplay.count
    }

这是返回要显示的单元格的函数:

 func collectionView(collectionView: UICollectionView,
        cellForItemAtIndexPath indexPath: NSIndexPath)
        -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCellWithReuseIdentifier(
                identifier,forIndexPath:indexPath) as! CustomCell

            let sticker = clothingStickersToDisplay[indexPath.row]
            let name = sticker.object["category"] as! String

            var imageView: MMImageView =
            createIconImageView(sticker.image, name: name)
            cell.setImageV(imageView)
            return cell
    }

编辑:哦,是的,我需要使用新的UICollectionView重新加载clothingStickersToDisplay我更新它的numberOfItemsInSection

1 个答案:

答案 0 :(得分:1)

我认为你应该做的是clothingStickersToDisplay一个全局数组声明。

而不是使用self.numberOfItems = clothingStickersToDisplay.count 将此功能更改为

func setStickersToDisplay(category: String) {
    clothingStickersToDisplay.removeAll()
    for item in self.allClothingStickers {
        let itemCategory = item.object["category"] as! String
        if itemCategory == category {
            clothingStickersToDisplay.append(item) //<---- this is good you have the data into the data Structure 
          // ----> just reload the collectionView
        }
    }

}

在numberOfItemsInSection()

return self.clothingStickersToDisplay.count
相关问题