如何使用 imagepickercontroller 将照片作为缩略图放入 collectionView 单元格中

how to get a photo with imagepickercontroller into the collectionView cell as thumbnail

我尝试创建一个代码来从相册中挑选照片并将其作为集合视图单元格中的缩略图显示在屏幕上。我将在每次单击按钮时选择一张照片,新照片将出现在上一张缩略图旁边。 CollectionView 将具有垂直滚动的单行。 我很难将图像从 pickercontroller didFinishPickingMediaWithInf 方法传输到 collectionView cellForItemAt 方法。我通过使用虚拟 UIImageV 找到了解决方案,但它只显示第一张照片而不显示其他照片。我没有遇到任何崩溃。您能帮我更正代码以将我从相册中选择的照片上传到集合视图单元格中吗?请看下面的代码:

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UIImagePickerControllerDelegate,UINavigationControllerDelegate {

    public let imagePicker = UIImagePickerController()
    
    @IBOutlet weak var dummyImageView: UIImageView!
    
    private let reuseIdentifier = "myViewCell"
    
    var myImage = [UIImage]()
    
    @IBOutlet var collectionView: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        dummyImageView.isHidden = true
        collectionView.dataSource = self
        collectionView.delegate = self
                
    }
        
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return myImage.count    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
       let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier , for: indexPath) as! MyViewCell
        
        cell.backgroundColor = UIColor.blue
        
        let imageView = cell.myImage
        myImage.append(dummyImageView.image!)
        imageView!.image = myImage[indexPath.row]
        
        return cell
        
    }

    @IBAction func imageButtonPressed(_ sender: Any) {
        
        imagePicker.delegate = self
        imagePicker.sourceType = .photoLibrary
        imagePicker.allowsEditing = false
         
        self.present(imagePicker, animated: true, completion: nil)
      
       
        }
      

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
    
        if  let image = info[.originalImage] as? UIImage{
            print("last value",myImage.count)
            
            dummyImageView.image = image
            myImage.append(dummyImageView.image!)
            
            collectionView.reloadData()
           
        
        } else {
            print("error to load")
        }
               
       dismiss(animated: true, completion: nil)    
    }
}

这个问题并不明显,所以我不得不在我的机器上重新创建它。实际上 myImage 数组在下面的函数中被加载了两次。

  1. didFinishPickingMediaWithInfo
  2. cellForItemAt

这会导致集合视图中的数据被添加到 myImage 数组中。 删除 cellForItemAt 中的以下分配,解决了这个问题。 // myImage.append(dummyImageView.image!)