Использование UIImagePickerController с UICollectionView - PullRequest
1 голос
/ 26 февраля 2020

Я работаю над куском кода с логикой c ниже:

- On every tap on a button, a new view opens and allows the user to choose an image from the phone's gallery.
- The chosen image should be loaded and displayed in an horizontal scroll view. 

Проблема, с которой я сталкиваюсь, заключается в том, что средство выбора закрывается нормально при выборе изображения, но изображение не загружается в UIcollectionView при отклонении средства выбора (изображение заполнителя остается и не заменяется выбранным изображением). В моей консоли не происходит сбоев или ошибок. Спасибо за любую помощь!

Вот мой контроллер вида для этой функции:

public class ImagePickerViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate, UICollectionViewDelegate, UICollectionViewDataSource {

    var mediaArray = [UIImage]()

    @IBAction func galleryButtonTapped(_ sender: Any) {
        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self

        let actionSheet = UIAlertController(title: "Gallery image", message: "Choose an image from your gallery", preferredStyle: .actionSheet)

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

        }))

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

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

    }

    public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage

        mediaArray.append(selectedImage)


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


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



    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return mediaArray.count
    }

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

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MediaCollectionViewCell", for: indexPath) as! MediaCollectionViewCell

        cell.mediaContent.image = mediaArray[indexPath.row]

        return cell
    }



}

вот часть моего вида горизонтальной прокрутки enter image description here

1 Ответ

2 голосов
/ 26 февраля 2020

Перезагрузите коллекцию, когда выбрано изображение.

public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage

        mediaArray.append(selectedImage)


        picker.dismiss(animated: true) {
            self.collectionView.reloadData()
        }
    }

...