有没有办法获得通知,当我的UIImageView.image属性更改?

有没有办法获得通知,当我的UIImageView.image属性更改?

问题描述:

有没有办法在UIImageView.image属性上设置观察者,所以我可以获得属性更改时的通知?也许与NSNotification?我将如何做这个?

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?

我有大量的UIImageViews,所以我需要知道哪一个发生了改变。

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.

这称为键值观察。可以观察到符合键值编码的任何对象,这包括具有属性的对象。阅读本节目指南关于KVO如何工作以及如何使用它。这是一个简短的例子(免责声明:它可能不工作)

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