开发者

Set value for a pointer in objective c?

开发者 https://www.devze.com 2023-01-23 21:06 出处:网络
I have 2 UIImageVIew: UIImageView *imageView1 = [[UIImageView alloc] init]; UIImageView *imageView2 = [[UIImageView alloc] init];

I have 2 UIImageVIew:

UIImageView *imageView1 = [[UIImageView alloc] init];
UIImageView *imageView2 = [[UIImageView alloc] init];

and one UIImage:

UIImag开发者_如何学运维e *image = [[UIImage alloc] imageWithNamed:@"image_name.png"];

so i set image for both of UIImageView with the same UIImage:

imageView1.image = image;
imageView2.image = image;

How can i change value of UIImage *image (Not point UIImage *image to another UIImage by: image = [[UIImage alloc] imageWithNamed:@"another_image_name.png"];). So when i do it, i want imageView1 and imageView2 display the same image (another_image_name.png)


UIImage instances are immutable, once they have been alloc'd and init'd, they cannot change. If you want to change the images for your image views, you need to alloc and init another UIImage instance (or use the convenience methods, e.g. +imageNamed: etc) and set it to both of your image views.

Image objects are immutable, so you cannot change their properties after creation


You can't modifty a UIImage so what you ask is impossible to do straightforwardly.

However, you could have imageView2 register as an observer on the image property of imageView1y using key value observing and when it observes a change it sets its image to the same one as in imageView1.

// To register for KVO
[imageView1 addObserver: imageView2
             forKeyPath: @"image"
                options: NSKeyValueObservingOptionNew
                context: NULL];

In imageView2, you'll need the following. You can either subclass UIImageView or add a category to it.

// method in imageView2 to deal with observations

- (void)observeValueForKeyPath: (NSString*) keyPath
                      ofObject: (id)object
                        change: (NSDictionary*)change
                       context: (void*) context
{
    if ([keyPath isEqual:@"image"]) 
    {
        [self setImage: [change objectForKey:NSKeyValueChangeNewKey]];
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号