2015-09-12 33 views
1

我想在運行時設置我的collectionView的numberOfItemsInSection。我會在運行時以編程方式更改值,並想知道如何。在運行時設置numberOfItemsInSection - UICollectionView

我有一個圖像數組顯示在我的UICollectionView(每個UICollectionViewCell有一個圖像),用戶可以更改要顯示的圖像的類別,這也會更改要顯示的圖像的數量。加載視圖時,numberOfItemsInSection設置爲allClothingStickers數組的計數。但是這個數字太高了。顯示的數組是clothingStickersToDisplay數組,它是allClothingStickers數組的子集。

有此錯誤的滾動後:

fatal error: Array index out of range

這是因爲項目的數量已經變得越來越小,但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

我想你應該做的是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