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

前端 未结 1 1524
滥情空心
滥情空心 2021-01-04 00:21

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 a

1条回答
  •  北海茫月
    2021-01-04 00:45

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

    0 讨论(0)
提交回复
热议问题