UICollectionViewCell не показывает изображения, выбранные из UIImagePickerController - PullRequest
0 голосов
/ 11 апреля 2019

Может ли кто-нибудь увидеть здесь какие-либо ошибки, которые мешают ячейке "photoInTheCellnow" отображать значения UIImage из изображения Picker

import UIKit
import Photos
import PhotosUI

class FirstViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    @IBOutlet weak var collectionView: UICollectionView!

    var photosInTheCellNow = [UIImage]()
    var imagePicker = UIImagePickerController()

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.delegate = self
        collectionView.dataSource = self
        imagePicker.delegate = self
    }

    @IBAction func openLibrary(_ sender: UIBarButtonItem) {

        let photoAuthorizationStatus = PHPhotoLibrary.authorizationStatus()

        switch photoAuthorizationStatus {
        case .authorized: print("Access is granted by user")
        case .notDetermined:
            PHPhotoLibrary.requestAuthorization({ (newStatus) in print("status is \(newStatus)"); if newStatus == PHAuthorizationStatus.authorized { print("success") } })
        case .restricted: print("User do not have access to photo album.")
        case .denied: print("User has denied the permission.")  
        }

        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self


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

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

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


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

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


        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotosCollectionViewCell", for: indexPath) as! PhotosCollectionViewCell

            return cell
        }

        func register(_ cellClass: PhotosCollectionViewCell, forCellWithReuseIdentifier identifier: String) { }
   }
}

Это пользовательский класс ячейки

import UIKit

class PhotosCollectionViewCell: UICollectionViewCell {


    @IBOutlet weak var imageView: UIImageView!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func prepareForReuse() {
        super.prepareForReuse()
    }
}

Ответы [ 2 ]

1 голос
/ 11 апреля 2019

Как уже упоминалось @RaziTiwana, вам нужно назначить изображение для вашей ячейки просмотра коллекции в cellForItemAt:indexPath.

cell.imageView.image =  photosInTheCellNow[indexPath.row]

Вам также необходимо обновить collectionView, как только вы выбрали изображение.Вы добавили изображение в свойство photosInTheCellNow, но не сообщили collectionView об изменении источника данных.Вы можете либо перезагрузить весь collectionView, вызвав collectionView.reloadData(), либо просто вставить последнюю строку, как показано здесь.

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

       photosInTheCellNow.append(image)
       let indexPath = IndexPath(item: photosInTheCellNow.count-1, section: 0)
       collectionView.insertItems(at: [indexPath])
       picker.dismiss(animated: true, completion: nil)
    }
0 голосов
/ 11 апреля 2019

Вы пропали без вести

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotosCollectionViewCell", for: indexPath) as! PhotosCollectionViewCell

    cell.imageView.image =  photosInTheCellNow[indexPath.row]

    return cell
}
...