【发布时间】:2012-05-09 00:41:05
【问题描述】:
有没有办法在 UIImageView.image 属性上设置观察者,以便我可以在属性更改时收到通知?也许与 NSNotification?我该怎么做呢?
我有大量的 UIImageView,所以我还需要知道发生在哪一个上。
我该怎么做?谢谢。
【问题讨论】:
标签: iphone objective-c ios xcode cocoa-touch
有没有办法在 UIImageView.image 属性上设置观察者,以便我可以在属性更改时收到通知?也许与 NSNotification?我该怎么做呢?
我有大量的 UIImageView,所以我还需要知道发生在哪一个上。
我该怎么做?谢谢。
【问题讨论】:
标签: iphone objective-c ios xcode cocoa-touch
这称为键值观察。可以观察到任何符合键值编码的对象,这包括具有属性的对象。阅读this programming guide,了解 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
}
}
【讨论】:
-dealloc中的观察者,像这样:[imageView removeObserver:self forKeyPath:@"image"];
在 Swift 中,使用KVO。例如
imageView.observe(\.image, options: [.new]) { [weak self] (object, change) in
// do something with image
}
更多讨论How i detect changes image in a UIImageView in Swift iOS
【讨论】: