Search code examples
swiftuiimageviewdidset

swift - didSet not called on UIImageView


How can I get didSet to recognize when imageView.image has been set? It only seems to be called during initialization.

@IBOutlet weak var imageView: UIImageView! {
   didSet {
      //do stuff
   }
}

Solution

  • didSet will only be called when you set the imageView itself. For example:

    imageView = UIImageView()
    

    This doesn't really make sense, since you already have an image view and it's working completely fine. What you're trying to do is to monitor changes in one of your image view's properties.

    To do this, try making a subclass of UIImageView, then observing changes in its image. Don't forget to set the custom class of your image view back in the storyboard, then reconnecting the outlet.

    class CustomImageView: UIImageView {
        override var image {
            didSet {
                /// do stuff
            }
        }
    }
    

    If you need to execute some code back in your view controller, try using a closure.

    class CustomImageView: UIImageView {
        var imageSet: (() -> Void)?
        override var image {
            didSet {
                imageSet?()
            }
        }
    }
    
    class ViewController: UIViewController {
        @IBOutlet weak var imageView: CustomImageView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            imageView.imageSet = {
                /// do stuff
            }
        }
    }
    

    Alternatively, you can use KVO.