有没有办法获得通知,当我的UIImageView.image属性更改? [英] Is there a way to get notified when my UIImageView.image property changes?

查看:114
本文介绍了有没有办法获得通知,当我的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
    }
}

这篇关于有没有办法获得通知,当我的UIImageView.image属性更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆