swift - 用用户选择的照片替换 Collection View 中的默认图像-swift

标签 swift uicollectionview uiimagepickercontroller phpickerviewcontroller

所以我有一个 Collection View ,它在每个单元格上填充三个默认图像。用户可以通过新的PHPicker选择图片,我要完成的是

  1. 用选定的照片替换默认图像,因此第一个选定的图像应该替换相机单元等......(通过底部的链接查看图像)
  2. 在用户删除所选图像时显示默认图像

目前,当我将一张新照片发送到 imgArray 时,它会显示在相机单元格之前的一个新单元格中,因为我正在使用如下插入方法:imgArray.insert(image, at: 0)。

我的代码:

  var imgArray = [UIImage(systemName: "camera"), UIImage(systemName: "photo"), UIImage(systemName: "photo")]

   func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "1", for: indexPath) as! CustomCell
    cell.imageView.image = imgArray[indexPath.row]
    cell.imageView.tintColor = .gray
    cell.imageView.layer.cornerRadius = 4
    return cell
}

 func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
    dismiss(animated: true, completion: nil)
    
    for item in results {
        
        item.itemProvider.loadObject(ofClass: UIImage.self) { image, error in

            if let image = image as? UIImage {
                DispatchQueue.main.async {
                    self.imgArray.insert(image, at: 0)
                    self.collectionView.reloadData()
                }
            }
        }
    }
}

我试过删除数组的第一项,然后像这样插入新照片:

                    self.imgArray.removeFirst(1)
                    self.imgArray.insert(image, at: 0)
                    self.collectionView.reloadData()

但是正如代码本身所说,这只会工作一次,之后所有替换都只在第一个单元格中进行。 那么在第一次更换后我怎样才能到达其他细胞呢?任何其他给出相同结果的方法都会对我有很大帮助。提前谢谢大家!

before selection

after selecting three images

最佳答案

一种方法是保留两个图像数组,[UIImage] 类型的 defaultImages[ UIImage?]defaultImages 将保存您的相机和照片图像,inputImages 将保存用户选择的图像。将图像初始化为:

defaultImages = [UIImage(systemName: "camera"), UIImage(systemName: "photo"), UIImage(systemName: "photo")]
inputImages: [UIImage?] = [nil, nil, nil]

要为索引 index 选择正确的照片,请使用:

image = inputImages[index] ?? defaultImages[index]

要在索引 index 处添加用户输入图像,请使用:

image: UIImage = ...  // Get the image.
inputImages[index] = image

要删除索引 index 处的用户输入图像,请使用:

inputImages[index] = nil

关于swift - 用用户选择的照片替换 Collection View 中的默认图像-swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69683774/

相关文章:

objective-c - objective-c 和 swift 中的不同格式掩码

ios - 尝试确定子类 UICollectionViewCell 中的单元格宽度

ios - "The file “IMG_xxxx.JPG” 无法打开,因为没有这样的文件。”

ios - 在 Swift 中将拾取的图像从 UIImagePicker 设置为 UIImageView

ios - 调用 imageWithData :UIImageJPEGRepresentation() multiple times only compresses image the first time

ios - 如何防止 UIPageViewController 的 setViewControllers 方法崩溃?

swift - 在 Swift 中将字符串附加到 NSMutableString

ios - 快速刷新控件时出错

ios - UITableviewCell 中垂直 UICollectionView 的数据输入

ios - 如何在 iOS swift 的 ARSCNView 中显示 uicollection View