【发布时间】:2016-09-11 23:49:31
【问题描述】:
我有一个 UICollection 视图,它在我启动应用程序时加载得很好。我的问题是,当单击菜单栏中的按钮时,我需要用新数据重新加载它。这是我的代码。为了简单起见,我已经大大缩减了它
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() 运行时出现此错误
致命错误:在展开可选值时意外发现 nil
关于如何正确执行此操作的任何想法?非常感谢任何帮助
PS。当我在viewDidLoad() 中运行reloadData() 时,数据符合预期
【问题讨论】:
-
尝试保持断点并检查哪个数据源方法产生了这个错误。
-
我认为你应该检查 currentImageArray 并在 currentImageArray 为 nil 时返回 0
标签: ios swift uicollectionview reload