简体   繁体   中英

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!

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM