Set image to another UIImageView

I'm trying to create a kind of settings page, and it's hard for me to switch the background image of my original view. So far, the code:

-(IBAction)switchBackground:(id)sender { ViewController *mainView = [[ViewController alloc] initWithNibName:nil bundle:nil]; mainView.displayedImage.image = [UIImage imageNamed:@"image.png"];; } 

Maybe I can get some pointers?

Thank you all.

+4
source share
1 answer

You create a new mainView every time you call the switchBackground method. You must change the background of an existing object to see how the change occurred.

From your code, it's hard to tell where the switchBackground method switchBackground . ViewController ?

If it is in the view controller, you only need to:

 self.displayedImage.image = [UIImage imageNamed:@"image.png"]; 

EDIT

According to your comment.

If you want to change the image of an object of class A from class B, you can do this in two ways:

1. Via the link to the object

it is an initializer of settings, which, when created, gets a pointer to an existing mainView

 @property(nonatomic,assign)ViewController *mainView; - (id)initWithMainViewController:(ViewController*)vc { self = [super init]; if (self) { self.mainView = vc; } return self; } -(IBAction)switchBackground:(id)sender { mainView.displayedImage.image = [UIImage imageNamed:@"image.png"]; } 

2. Publishing a local notification through NSNotificationCenter.

 -(IBAction)switchBackground:(id)sender { [[NSNotificationCenter defaultCenter] postNotificationName: @"changeImage" object: [UIImage imageNamed:@"image.png"]]; } 

Now in your ViewController listen to the notification and respond

in the init method in ViewController

 - (id)initWithMainViewController:(ViewController*)vc { self = [super init]; if (self) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeImage:) name:@"changeImage" object:nil]; } return self; } -(void)changeImage:(NSNotification*)notification{ self.displayedImage.image = (UIImage*) notification.object; } 
+4
source

Source: https://habr.com/ru/post/1388755/


All Articles