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
CodePudding user response:
add tag to 4 buttons as: 0, 1, 2, 3. create an array of images
var currentTag = 0
var images:[UIImage] = [UIImage(),UIImage(),UIImage(),UIImage()] {
didSet {
for (index,imageView) in layout1Images.enumerated() {
imageView.image = images[index]
}
}
}
@IBAction func openImagePicker(_ sender: UIButton) {
currentTag = sender.tag
let picker = UIImagePickerController()
picker.allowsEditing = true
picker.delegate = self
present(picker, animated: true)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let image = info[.editedImage] as? UIImage else { return }
images.remove(at: currentTag)
images.insert(image, at: currentTag)
//How to return the image to the selected UIImageView ?
dismiss(animated: true)
}
CodePudding user response:
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