Search code examples
swifttableviewuiimagepickercontroller

Change image of custom cell with UIImagePickerController


I’ve created a custom cell that has imageView inside. I want to change the image of that imageView with the help of UIImagePickerController. When I check this function in the simulator, it doesn’t change anything. Can’t figure out the problem.

The property of the custom cell:

let imageOfPlace: UIImageView = {
    let iv = UIImageView()
    return iv
}()

The cell in tableView:

let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
        if indexPath.row == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: ImageOfPlaceViewCell.identifierOfImageOfPlaceCell) as! ImageOfPlaceViewCell

Functions of picker:

func chooseImagePickerController(source: UIImagePickerController.SourceType) {
    if UIImagePickerController.isSourceTypeAvailable(source) {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.allowsEditing = true
        imagePicker.sourceType = source
        present(imagePicker, animated: true)
    }
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    let myCell = ImageOfPlaceViewCell()
    myCell.imageOfPlace.image = info[.editedImage] as! UIImage
    picker.dismiss(animated: true)
}

Solution

  • You're creating a new cell here:

    let myCell = ImageOfPlaceViewCell()
    

    Instead of that you need to change image of an existing cell. You need to get an existing cell object from the table. To do this you can use tableView.cellForRow, and pass there index path of your row.

    I'm not sure about your table structure, but you also need to make sure that when you reload your table it won't disappear, so you can store picked image somewhere else to use next time in cellForRowAt.

    var pickedImage: UIImage?
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: ImageOfPlaceViewCell.identifierOfImageOfPlaceCell) as! ImageOfPlaceViewCell
            cell.imageOfPlace.image = pickedImage
        }
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
        let image = info[.editedImage] as! UIImage
        pickedImage = image
    
        let myCell = tableView.cellForRow(at: IndexPath(row: 0, section: 0))
    
        myCell?.imageOfPlace.image = info[.editedImage] as! UIImage
    
        picker.dismiss(animated: true)
    }
    

    p.s. Also I'm not sure what's this let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! before your if, it's probably redundant(at least in case when you return cell from that if)