【发布时间】:2018-01-25 16:50:02
【问题描述】:
我正在尝试将数据从一个视图控制器添加到集合视图控制器,该控制器将元素添加到数据源数组,然后将单元格添加到集合视图。
prepareforsegue 之前的ViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "unwindToCollectionView"{
let CVC = segue.destination as! CollectionViewController
if let image = image{
CVC.images.insert(imagePost(image:image), at: 0)
print("Image is not nil")
}
let index = IndexPath(item: 0, section: 0)
//CVC.collectionView?.reloadData()
CVC.collectionView?.collectionViewLayout.invalidateLayout()
CVC.collectionView?.layoutIfNeeded()
CVC.collectionView?.insertItems(at: [index])
//CVC.collectionView?.reloadItems(at: [index])
print("In prepare for segue: \(CVC.images.count)")
}
}
collectionViewControllercellForItemAt
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
// Configure the cell
cell.cellImageView.image = images[indexPath.row].image
cell.cellImageView.clipsToBounds = true
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0)
layout.itemSize = CGSize(width: (UIScreen.main.bounds.width-1)/2, height: (UIScreen.main.bounds.width-1)/2)
layout.minimumInteritemSpacing = 1
layout.minimumLineSpacing = 1
collectionView.collectionViewLayout = layout
cell.cellImageView.layer.cornerRadius = CGFloat((cell.cellImageView.frame.width)/2)
return cell
}
收到错误:
2018-01-25 11:43:16.228902-0500 CAR+CV(1.0)Server[4182:1181750] *** 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“无法设置布局 [] [;层 = ;内容偏移:{0,-88};内容大小:{375, 573}; adjustedContentInset: {88, 0, 83, 0}> 集合视图布局: ] 在更新期间。
【问题讨论】:
-
您为什么在
prepareForSegue中调用invalidateLayout、layoutIfNeeded和insertItems?另外我认为您不应该在cellForItemAtIndexPath中设置UICollectionViewFlowLayout……为什么不使用UICollectionViewDelegateFlowLayout协议中的方法? -
@shim 如果不在
prepareForSegue中,应该在哪里调用insertItems当我尝试删除它并在collectionViewController的viewDidLoad内调用它时,我收到了有关索引的错误。 -
也许你误解了
insertItems的目的。您只需要设置cellForItemAt和numberOfItemsInSection并且集合视图会自行处理插入项目。insertItems主要用于当您需要显示正在添加的新项目时 - 并且必须在集合视图的数据源中进行相应的更改。 -
@shim 我在 segue 之后传递了一个带有添加项的数组。当我不在
prepareForSegue中调用insertItems时,collectionView 中不会生成新单元格
标签: ios swift uicollectionview uicollectionviewcell uicollectionviewlayout