xcode 有没有办法在我的 UIImageView.image 属性更改时收到通知?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10508422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to get notified when my UIImageView.image property changes?
提问by Ethan Allen
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?
有没有办法在 UIImageView.image 属性上设置观察者,以便我可以在属性更改时收到通知?也许使用 NSNotification?我该怎么做呢?
I have a large number of UIImageViews, so I'll need to know which one the change occurred on as well.
我有大量的 UIImageViews,所以我还需要知道更改发生在哪一个上。
How do I do this? Thanks.
我该怎么做呢?谢谢。
回答by dreamlax
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 guideon how KVO works and how to use it. Here is a short example (disclaimer: it might not work)
这称为键值观察。任何符合键值编码的对象都可以被观察到,这包括具有属性的对象。阅读本编程指南,了解 KVO 的工作原理和使用方法。这是一个简短的例子(免责声明:它可能不起作用)
- (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
}
}