skip to Main Content

I’m new to programming and Swift and I can’t find a solution to my problem :

I have 4 UIImageView with an UIButton on top of each image.
When I tap a UIButton, I want to open an UIImagePickerController, select an image and place it in the UIImageView associated (here’s a screen of my Interface Builder)

I’ve placed my UIImageView in an outlet collection

@IBOutlet var layout1Images: [UIImageView]!

Here’s my IBAction linked to my 4 buttons :

@IBAction func openImagePicker(_ sender: UIButton) {
    for image in layout1Images {
        if sender.tag == image.tag {
            
            let picker = UIImagePickerController()
            picker.allowsEditing = true
            picker.delegate = self
            present(picker, animated: true)
            
        }
    }
}

And my imagePickerController :

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    guard let image = info[.editedImage] as? UIImage else { return }
    
    //How to return the image to the selected UIImageView ?
            
    dismiss(animated: true)
}

How can I return the image to the selected UIImageView ?

Thanks for your help

2

Answers


  1. First of all store the tag you are getting from UIButton in a variable like

    var selectedTag = 0
    

    in openImagePicker() Action add the following line

    selectedTag = sender.tag
    

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

    add this line

    layoutImages[selectedTag].image = image
    
    Login or Signup to reply.
  2. func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
           guard let image = info[.originalImage] as? UIImage else {
                      fatalError("Expected a dictionary containing an image, but was provided the following: (info)")
                  }
    // make use of the image
       }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search