I am trying to select an image from the user's phone and update an image view with said image.
The problem I am having is that it won't update the image. It does get there as I added a breakpoint and it hit the breakpoint, and the image view can change image as I manually tried changing it elsewhere.
But it refuses to work when I need it.
My image view:
lazy var profilePictureImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "DefaultUser")
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleSelectProfilePicture)))
imageView.isUserInteractionEnabled = true
return imageView
}()
The code to update the image via picking a photo on the device:
import UIKit
extension ProfileVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func handleSelectProfilePicture() {
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
present(picker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var selectedImageFromPicker: UIImage?
if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
selectedImageFromPicker = editedImage
}
else if let originalImage = info["UIImagePickerControllerOriginalImage"] as? UIImage {
selectedImageFromPicker = originalImage
}
if let selectedImage = selectedImageFromPicker {
profilePictureImageView.image = selectedImage
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
}
[EDIT] One thing I have discovered is if I try it on a different VC with a different image view it works as intended. The only main difference I can see between the two VC's is the one I want it to work on but won't also extends 'UIPickerViewDelegate' and 'UIPickerViewDataSource'. Could there be conflict?
Try to set modalPresentationStyle tooverCurrentContext Like the sample below
let myPickerController = UIImagePickerController()
myPickerController.delegate = self
myPickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary
**myPickerController.modalPresentationStyle = .overCurrentContext**
myPickerController.delegate = self
present(myPickerController, animated: true, completion: nil)
Try this, it worked for me:
DispatchQueue.main.async {
profilePictureImageView.image = croppedImage
profilePictureImageView.setNeedsDisplay()
}
Essentially you need to specify that you want to update the image via
profilePictureImageView.setNeedsDisplay()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With