2016-05-16 90 views
0

我有一個UICollection視圖,在啓動應用程序時加載得很好。我的問題是,當點擊菜單欄中的按鈕時,我需要重新加載新數據。這是我的代碼。爲了簡單起見,我已經大大削減下來如何從另一個函數觸發UICollectionView的重載方法

class RootViewController: UIViewController,UICollectionViewDelegateFlowLayout, UICollectionViewDataSource{//The view controller that contains the collection view 
     var carouselCollectionView: UICollectionView!//A reference to the collectionview 
     override func viewDidLoad() { 
      super.viewDidLoad() 

      let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() 
      layout.sectionInset = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1) 
      layout.itemSize = CGSize(width: carouselWindowWidth, height: carouselWindowHeight) 
      layout.scrollDirection = UICollectionViewScrollDirection.Horizontal 
      layout.minimumInteritemSpacing = 5 
      layout.minimumLineSpacing = 5 

      carouselCollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout) 
      carouselCollectionView.frame = CGRectMake(0,0,200,200) 
      carouselCollectionView.delegate = self 
      carouselCollectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell") 
      carouselCollectionView.backgroundColor = UIColor.clearColor() 

      self.view.addSubview(carouselCollectionView) //Add the collectionview to the main view(self) 
     }//End viewDidLoad 


     //Delegates for collectionViewController go here 
     func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
      return currentImageArray.count 
     } 


     func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
      let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) 
      /*...*/ 
     } 

     func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 
      /*...*/ 
     } 


     //This function is triggered when a menuItem on the menuBar is clicked. It it supposed to fetch some data from some source, then reload the collectionview 
     func reloadData(VC:UIViewController){ 
      /*...*/ 
      carouselCollectionView.reloadData() 
     } 

    }//End RootViewController 

我得到這個錯誤時reloadData()運行

fatal error: unexpectedly found nil while unwrapping an Optional value

關於如何正確做到這一點任何想法?任何幫助非常感謝

PS。如預期的數據時,我內viewDidLoad()

+0

嘗試保持斷點並檢查哪個數據源方法正在生成此錯誤。 –

+0

我想你應該檢查currentImageArray並返回0如果currentImageArray是零 – Tien

回答

-1

好的運行reloadData()您需要使用2個步驟來處理這個問題:

  1. 創建集合視圖的@IBOutlet並將其與你的故事板集合視圖連接:yourCollectionView

  2. 聲明並初始化:VAR currentImageArray = UIImage的

  3. 在您的按鈕@IBAction:

//做你的東西 //然後

yourCollectionView.reloadData()

讓它工作時我知道!

+0

傾斜:不能這樣做,因爲我的整個應用程序是以編程方式編寫的(沒有故事板) –

+0

嗯。當你用一個變量強制展開變量時,會發生錯誤!認爲它不會是零......但它似乎是。嘗試檢查將值賦給單元格的行......如果您試圖強制解包任何值....還要檢查'currentImageArray'是否不爲零....讓我知道會發生什麼 – Mangesh

相關問題