Search code examples
swiftuicollectionviewuiimagepickercontrollerswift5

swift 5.1 Adding images from UIImagePickerController to an array that gets added to a UICollectionView


This is my code so far. When I click on images in the library, it appends to the array, but the collectionView does not display the image nor adds to the collectionView.

@IBOutlet weak var collectionView: UICollectionView!

let imagePicker = UIImagePickerController()
// Array that handles the images to the collectionView.
var photoArray: [UIImage] = []


override func viewDidLoad() {
    super.viewDidLoad()

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

// Button that requests the UIImagePicker
@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
    
    imagePicker.allowsEditing = false
    imagePicker.sourceType = .photoLibrary
    
    present(imagePicker, animated: true)
    
}

// MARK: - UIPickerControllerDelegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo 
info: [UIImagePickerController.InfoKey : Any]) {
    
    if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
        photoArray.append(pickedImage)
    }
}

// MARK: - collectionView DataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) 
-> Int {
    return photoArray.count
}

Adding the array to the collectionView

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) 
-> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CELL", 
for: indexPath) as! PhotosCell
    cell.photoImageView.image = photoArray[indexPath.row]
    
    return cell
}

Solution

  • Reload the collectionView once you've picked the image.

    func imagePickerController(
        _ picker: UIImagePickerController,
        didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
    
        if let pickedImage = info[.originalImage] as? UIImage {
            photoArray.append(pickedImage)
            collectionView.reloadData()
        }
    }