使用ImagePicker上传图片到CollectionView

Use ImagePicker to upload images into CollectionView

我正在尝试允许用户 select 或通过 UIPickerView 拍摄图像,然后将 selected 图像添加到集合视图单元格,创建自定义相册。当我 select 图像时,集合视图中没有任何内容。如果有人有解决方案或知道更好的方法,请回复,因为我对编程还比较陌生。谢谢。

class ViewController: UICollectionViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UICollectionViewDelegateFlowLayout {


@IBOutlet weak var imageViewTwo: UIImageView!

    var imageArray = [UIImage]()

override func viewDidLoad() {
super.viewDidLoad()
imageViewTwo.isHidden = true
}



@IBAction func chooseImage(_ sender: UIBarButtonItem) {

let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self

let actionSheet = UIAlertController(title: "Photo Source", message: "Choose a Source", preferredStyle: .actionSheet)

actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action: UIAlertAction) in

if UIImagePickerController.isSourceTypeAvailable(.camera) {
imagePickerController.sourceType = .camera
self.present(imagePickerController, animated: true, completion: nil)
} else {
print("Camera is not available.")
}

}))

actionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { (action: UIAlertAction) in
imagePickerController.sourceType = .photoLibrary
self.present(imagePickerController, animated: true, completion: nil)
}))

actionSheet.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))

self.present(actionSheet, animated: true, completion: nil)

}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage

    imageViewTwo.image = image
    imageArray.append(imageViewTwo.image!)


picker.dismiss(animated: true, completion: nil)
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
    }





override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return imageArray.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)

    let imageView = cell.viewWithTag(1) as! UIImageView
    imageArray.append(imageViewTwo.image!)
    imageView.image = imageArray[indexPath.row]

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let width = collectionView.frame.width / 3 - 1

    return CGSize(width: width, height: width)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 1.0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 1.0
    }

}

将新图像附加到数据源后,调用 YOUR_COLLECTION_VIEW.reloadData() 只是为了显示最近添加到其数据源的新项目。

在 UICollectionViewCell 中显示图像并使用 imagepicker 更改图像并在数据中添加新图像。

// --------------------------------------------------------
// MARK:- Collection View and ImagePicker
// --------------------------------------------------------

  extension EditVideoVC : UICollectionViewDataSource, 
  UICollectionViewDelegate, UIImagePickerControllerDelegate, 
  UINavigationControllerDelegate{

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return imgArr.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImagePickerCell", for: indexPath) as! ImagePickerCell
    
    ///# Video Images Show on UICollectionCell with path #///
    
    cell._imgAdd.image = UIImage(contentsOfFile: (imgArr[indexPath.row]).path)
    
    cell.btnImgAdd.addTarget(self, action: #selector(handlebtnImgAddTapped(sender:)), for: .touchUpInside)
    cell.btnImgAdd.tag = indexPath.row

    return cell
}

@objc func handlebtnImgAddTapped(sender : UIButton){
    let imagePickerController = UIImagePickerController()
    imagePickerController.sourceType = .photoLibrary
    imagePickerController.delegate = self
    imagePickerController.accessibilityLabel = "\(sender.tag)"
    imagePickerController.allowsEditing = true
    self.present(imagePickerController, animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    
    if let image = info[UIImagePickerController.InfoKey.imageURL] as? URL, let index = Int(picker.accessibilityLabel ?? ""){
        
        self.imgArr[index] = image ///* change image on picker collectioncell at index *///
        
        let newImage = imagesArr[index] ///* set new image with old image name at index *///
        
        let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) [0] as NSString).appendingPathComponent("MyZipFiles")
        
        let filePath = URL(fileURLWithPath: path).appendingPathComponent("\(self.id)/\(self.titleVideo)") ///* inside folder all files *///
        print(filePath)
        
        
        let newimagePath = filePath.appendingPathComponent(newImage)
    
        do{
            ///# write imagedata to path for change image #///
            
            let data = try Data(contentsOf: image) ///* convert url into data *///
            
            if let imageData = UIImage(data: data)?.jpegData(compressionQuality: 0.5){
                try imageData.write(to: newimagePath, options: .atomic)
            }
        }
        catch {
            print(error.localizedDescription)
            }
        
        picker.dismiss(animated: true, completion: { () -> Void in
        self._pickerCollectionView.reloadData()
    })
    }
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    
    picker.dismiss(animated: true, completion: nil)
}
}