我有一個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()
嘗試保持斷點並檢查哪個數據源方法正在生成此錯誤。 –
我想你應該檢查currentImageArray並返回0如果currentImageArray是零 – Tien