【问题标题】:Replacing default images in a collection view with user selected photos- swift用用户选择的照片替换集合视图中的默认图像 - swift
【发布时间】:2021-12-09 12:07:35
【问题描述】:

所以我有一个集合视图,它在每个单元格上填充三个默认图像。用户可以通过新的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

【问题讨论】:

    标签: swift uicollectionview uiimagepickercontroller phpickerviewcontroller


    【解决方案1】:

    一种方法是保留两个图像数组,defaultImages 类型为 [UIImage]inputImages 类型为 [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
    

    【讨论】:

    • 我实际上已经用类似的想法解决了这个问题,即拥有 2 个数组,然后我使用 switch 语句检查用户是否选择了任何图像,否则将显示默认图像。无论如何感谢您的回答!
    猜你喜欢
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-26
    • 1970-01-01
    • 2012-10-09
    • 2017-04-16
    相关资源
    最近更新 更多