Is there a way to set an observer on a UIImageView.image property, so I can get notified of when the property has been changed? Perhaps with NSNotification? How would I go about doing this?
I have a large number of UIImageViews, so I'll need to know which one the change occurred on as well.
How do I do this? Thanks.
Open the Library, look for "Tap Gesture Recognizer" object. Drag the object to your storyboard, and set the delegate to the image you want to trigger actions. Then go to the view controller, drag the same object to set the IBAction.
Once you have an Image you can then set UIImageView: [imageView setImage:image]; The line above assumes imageView is your IBOutlet. That's it!
If that property is set to nil , the image view applies a default highlight to this image. If the animationImages property contains a valid set of images, those images are used instead. Changing the image in this property does not automatically change the size of the image view.
An object that manages image data in your app.
This is called Key-Value Observing. Any object that is Key-Value Coding compliant can be observed, and this includes objects with properties. Have a read of this programming guide on how KVO works and how to use it. Here is a short example (disclaimer: it might not work)
- (id) init
{
self = [super init];
if (!self) return nil;
// imageView is a UIImageView
[imageView addObserver:self
forKeyPath:@"image"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:NULL];
return self;
}
- (void) observeValueForKeyPath:(NSString *)path ofObject:(id) object change:(NSDictionary *) change context:(void *)context
{
// this method is used for all observations, so you need to make sure
// you are responding to the right one.
if (object == imageView && [path isEqualToString:@"image"])
{
UIImage *newImage = [change objectForKey:NSKeyValueChangeNewKey];
UIImage *oldImage = [change objectForKey:NSKeyValueChangeOldKey];
// oldImage is the image *before* the property changed
// newImage is the image *after* the property changed
}
}
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