Search code examples
iosswiftuitableviewuiimagepickercontroller

Using UIImagePickerController in each tableview cell


I'm trying to build a recipe app with a recipe upload function. In the PostController, there will be a tableview of all the cooking steps, each in a tableview cell. in the cell there will be a textfield of description and a UIImageView for picture upload ( the picture chosen from pickerController will be displayed in this UIImageView for later upload). I'm trying to do imageViewInCell.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleImageUpload))) to call thehandleImageUpload() function that generates a UIImagePickerController. But by doing this, I met two problems.

  1. I cannot get the index.row value of the cell by the selector in UITapGestureRecognizer , with out the index I cannot assign the chosen image back to the UIImageView of the cell.
  2. Even if I got index.row in handleImageUpload, I still need the function below to assign selected image. How would this function accept my parameter and find the corresponding imageViewInCell?

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let selectedImage: UIImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
             imageViewInCell.image = selectedImage
        }
        dismiss(animated: true, completion: nil)
    }
    

Solution

  • you can set the indexPath.row as the tag of your imageview in cellForRowAtIndexPath like Below

    cell.yourImageView.tag = indexPath.row
    

    and then you can get this indepath backagain using below

      let indexPath = NSIndexPath(forRow: sender.tag, inSection: 0)
    let cell = tableView.cellForRowAtIndexPath(indexPath) as! yourcellClass!
    cell.yourImgeView.image = selectedImage