Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get notified when my UIImageView.image property changes?

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.

like image 489
Ethan Allen Avatar asked May 09 '12 00:05

Ethan Allen


People also ask

How do I add actions to UIImageView?

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.

How do I change my picture on UIImageView?

Once you have an Image you can then set UIImageView: [imageView setImage:image]; The line above assumes imageView is your IBOutlet. That's it!

What happens when you set an imageView image property to nil?

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.

What is UIImage in swift?

An object that manages image data in your app.


1 Answers

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
    }
}
like image 131
dreamlax Avatar answered Oct 23 '22 15:10

dreamlax