【问题标题】:Convert an IndexPath array to a UIImage array将 IndexPath 数组转换为 UIImage 数组
【发布时间】: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 的原因是因为用户需要能够编辑图像,但是如果他们在图像中间停下来并返回,则需要保存用户的进度。如果他们关闭应用程序,进度将丢失。我不再认为我需要存储图像本身,只是对库中图像的引用。如果我错了,请纠正我。

【问题讨论】:

    标签: ios arrays swift xcode


    【解决方案1】:

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

    然后像在 cellForRow(at: indexPath) 中一样使用这些索引路径访问您的数据源。 因此,假设您有一个名为 func object(at indexPath: IndexPath) -> YourObjectModel 的助手 然后您可以使用数组的映射功能“转换” indexpath 数组。

    此外,图像不应最终存储在 coredata 中……只是对它的引用。

    【讨论】:

    • 我不确定我是否理解您的所有回复。我正在使用“indexPathsForSelectedItems”(参见“let curSelected: [IndexPath]”行)。我也在使用重新加载策略,这样当用户取消选择一个项目时,单元格将被重新编号。例如,如果他们选择“1、2、3、4”然后取消选择“2”,则单元格将重新编号为“1、2、3”而不是“1、3、4”。也许我错过了一些东西。你能展示一个解决方案/例子吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多