【发布时间】:2020-08-07 14:03:18
【问题描述】:
我正在开发一个使用 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)
}
}
我还尝试了以下代码,用完成处理程序替换了dismiss以强制重新加载:
let presentingVC = self.presentingViewController as! MyCollectionsViewController
self.dismiss(animated: true, completion: {presentingVC.viewWillAppear(true)})
它有效,但仅适用于第一次删除。之后由于索引超出范围错误再次崩溃。
【问题讨论】:
-
使用委托或 NotificationCenter 将新数组的计数从 InspectPhotoController 发送回 MyCollectionsViewController,将 MyCollectionsViewController 中的数组计数与返回的计数进行比较,如果计数不同,则调用 reloadData()。
-
你能详细说明一下吗,举个例子?同时,我尝试了以下代码: let presentingVC = self.presentingViewController as! MyCollectionsViewController self.dismiss(animated: true, completion: {presentingVC.viewWillAppear(true)}) 。它仅适用于第一次删除,之后再次崩溃。