【发布时间】:2020-10-21 05:32:00
【问题描述】:
我正在尝试创建一组从集合视图中选择的图像/视频,并使用 Core Data 存储它们。我有一个选定单元格的数组,它是动态的,因为它允许用户通过选择或取消选择单元格来向数组添加或减去图像。我的代码目前使用 IndexPath 来完成此操作,但我相信我需要将其转换为 UIImage 数组,以便可以将其添加到 Core Data based on another solution I saw。那么如何将下面的 selectedCells 数组转换为 UIImage 数组呢?
var selectedCells: [IndexPath] = []
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath) as? ImageCell {
selectedCells.append(indexPath)
cell.index = selectedCells.count
}
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
guard let idx = selectedCells.firstIndex(of: indexPath) else { return }
selectedCells.remove(at: idx)
let curSelected: [IndexPath] = collectionView.indexPathsForSelectedItems ?? []
collectionView.reloadData()
let saveY = collectionView.contentOffset.y
collectionView.performBatchUpdates({
curSelected.forEach { pth in
collectionView.selectItem(at: pth, animated: false, scrollPosition: .centeredVertically)
}
}, completion: { _ in
collectionView.contentOffset.y = saveY
})
}
更新: 我决定使用 Core Data 的原因是因为用户需要能够编辑图像,但是如果他们在图像中间停下来并返回,则需要保存用户的进度。如果他们关闭应用程序,进度将丢失。我不再认为我需要存储图像本身,只是对库中图像的引用。如果我错了,请纠正我。
【问题讨论】: