我正在开发一个使用UICollectionView显示一组图像的应用程序。用户可以单击图像,然后将其隔离到另一个视图控制器,然后检查图像。用户可以单击删除按钮删除图像文件,然后返回到当前的CollectionView。问题在于,由于索引现在“超出范围”,因此似乎项数未更新并且CollectionView将崩溃。我试图在几个地方添加reloadData(),但没有帮助。有什么想法在关闭显示的ViewController之后如何刷新项目计数?似乎在关闭并更新项目计数时未执行viewWillAppear。代码的关键部分如下。
class MyCollectionsViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
override func viewWillAppear(_ animated: Bool) {
myCollectionView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
collectionView.reloadData()
// find out how many image files
var files = listPhotos(subdir: "myCollections"). // listPhotos is a func to list the image file
return String(describing: files).components(separatedBy: ",").count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
// here to display images
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
var imagePath = ""
// find out the path of the image file
imagePathSelected = String(String(describing: listPhotos(subdir: "myCollections")[indexPath.item]).dropFirst(16))
}
// segue to another view controller
self.performSegue(withIdentifier: "InspectPhotoSegue", sender: imagePathSelected)
}
}
class InspectPhotoController: UIViewController {
@IBAction func deletePhoto(_ sender: Any) {
// here I delete the image file and then return to the presenting view controller
self.dismiss(animated: true, completion: nil)
}
}
我还尝试了以下代码,用完成处理程序替换解除以强制重新加载:
let presentingVC = self.presentingViewController as! MyCollectionsViewController
self.dismiss(animated: true, completion: {presentingVC.viewWillAppear(true)})
它有效,但仅适用于第一次删除。之后,由于索引超出范围错误,它再次崩溃。
答案 0 :(得分:1)
首先从numberOfItemsInSection中删除collectionView.reloadData()。
在您的MyCollectionsViewController中添加此
var selectedImageIndexPath: IndexPath!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let inspectController = segue.destination as? InspectPhotoController else {return}
inspectController.itemDeleted = {
self.listPhotos.remove(at: selectedImageIndexPath.row)
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
并在MyCollectionsViewController的didSelectItemAt Indexpath方法中添加以下内容:
self.selectedImageIndexPath = indexPath
然后在您的InspectPhotoController中添加以下回调:
var itemDeleted: (()->Void)?
并在删除图片时像这样调用此回调函数:
self.itemDeleted?() self.dismiss(动画:true)