【发布时间】:2017-01-06 15:49:55
【问题描述】:
我在一个视图控制器中有两个集合视图。顶部集合视图是空的,我希望当我在下部集合视图中选择任何项目时,该项目会添加到顶部集合视图中。问题是当我在下部集合视图中选择项目时应用程序崩溃并且我收到此错误:
原因:'无效更新:第 0 节中的项目数无效。更新后现有节中包含的项目数 (1) 必须等于更新前该节中包含的项目数 (0) ,加上或减去从该部分插入或删除的项目数(0 插入,0 删除),加上或减去移入或移出该部分的项目数(0 移入,0 移出)。'
有我的代码,怎么解决这个问题?
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
self.collectionView.collectionViewLayout = flowLayout
flowLayout.estimatedItemSize = CGSize(width: collectionView.bounds.width/3, height:32)
flowLayout.minimumLineSpacing = 2
flowLayout.minimumInteritemSpacing = 2
let flowLayout1 = self.topCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
self.topCollectionView.collectionViewLayout = flowLayout1
flowLayout1.estimatedItemSize = CGSize(width: collectionView.bounds.width/3, height:32)
flowLayout1.minimumLineSpacing = 2
flowLayout1.minimumInteritemSpacing = 2
self.collectionView.collectionViewLayout.invalidateLayout()
self.topCollectionView.collectionViewLayout.invalidateLayout()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == self.collectionView {
return foodData.count
}
else {
return selectFood.count
}
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LCell", for: indexPath)as! CollectionLabelCell
if collectionView == self.collectionView {
cell.titleLabel.text = foodData[indexPath.row]
}
else if collectionView == self.topCollectionView {
if selectFood.count != 0 {
cell.titleLabel.text = selectFood[indexPath.row]
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView == self.collectionView {
self.selectFood.append(foodData[indexPath.row])
self.topCollectionView.performBatchUpdates({ () -> Void in
self.topCollectionView.reloadData()
}, completion:nil)
}
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.bounds.width/3, height:32)
}
【问题讨论】:
标签: ios swift uicollectionview