将IndexPath数组转换为UIImage数组



我正在尝试创建一组从集合视图中选择的图像/视频,并使用核心数据进行存储。我有一个选定单元格的数组,它是动态的,因为它允许用户通过选择或取消选择单元格来向数组添加或减去图像。我的代码目前使用IndexPath来实现这一点,但我认为我需要将其转换为UIImage数组,以便根据我看到的另一个解决方案将其添加到核心数据中。那么,如何将下面的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
})
}

更新:我决定使用核心数据的原因是,用户需要能够编辑图像,但如果他们中途停止并返回,则需要保存用户的进度。如果他们关闭应用程序,进度将丢失。我不再认为我需要存储图像本身,只是对库中图像的引用。如果我错了,请纠正我。

您甚至不需要持有自己的selectedCells,有一个名为"indexPathsForSelectedItems;为此目的。您的重新加载策略使事情过于复杂。

然后像在cellForRow中那样使用这些索引路径来访问数据源(位于:indexPath(。假设您有一个名为func对象的助手(位于indexPath:indexPath(->YourObjectModel那么你可以";转换";indexpath数组使用数组的映射功能。

此外,图像不应该最终存储在核心数据中。。。只是对它的引用。

最新更新