2016-05-16 21 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

相关问题