Lê Khánh Vinh
Lê Khánh Vinh

Reputation: 2611

ios Swift 3 using Property Observer update Image from UIImagePicker

Hi I'm using IOS swift 3 to let user pick images from library or album.
I have an UIImage variable.
How can we use property Observer to update the UIImage when user finished pick an Image

Some thing like

var image: UIImage = {
    didSet....
 }

Currently I'm doing this

func show(image: UIImage) {
   imageView.image = image
   imageView.isHidden = false
   imageView.frame = CGRect(x: 10, y: 10, width: 260, height: 260)
       addPhotoLabel.isHidden = true
}


func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {

   image = info[UIImagePickerControllerEditedImage] as? UIImage
   if let theImage = image {
     show(image: theImage)
   }
   dismiss(animated: true, completion: nil)
}

Thinking of using property Observer to improve the approach.
Any help is much appreciate.

Thanks!

Upvotes: 1

Views: 1001

Answers (1)

rmaddy
rmaddy

Reputation: 318824

If you really want to update the image view any time the image property is set, then simply put all of the code in your show method in the didSet block for the image property.

var image: UIImage = {
    didSet {
        imageView.image = image
        imageView.isHidden = false
        imageView.frame = CGRect(x: 10, y: 10, width: 260, height: 260)
        addPhotoLabel.isHidden = true
    }
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let theImage = info[UIImagePickerControllerEditedImage] as? UIImage {
        image = theImage
    }

    picker.dismiss(animated: true, completion: nil)
}

Upvotes: 2

Related Questions