【问题标题】:Use ImagePicker to upload images into CollectionView使用 ImagePicker 将图片上传到 CollectionView
【发布时间】:2019-03-13 09:31:05
【问题描述】:

我试图让用户通过 UIPickerView 选择或获取图像,并将所选图像添加到集合视图单元格中,从而创建自定义相册。当我选择一个图像时,集合视图中不会出现任何内容。如果有人有解决方案或知道更好的方法来做到这一点,请回复,因为我对编程比较陌生。谢谢。

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
    }

}

【问题讨论】:

  • 您需要告诉集合视图您对数据模型所做的更新。
  • 感谢您的快速响应,但我该怎么做呢? @rmaddy
  • reloadDatainsertItems.
  • 有效!谢谢!
  • 但是,图像每次都会成倍增加……这是因为我放置了 reloadData() 吗?我把它放在 imagePicker didFinishPickingMediaWithInfo 函数中。

标签: ios swift uicollectionviewcell uipickerview


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    在 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)
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      • 2018-03-26
      • 2018-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多