Reputation: 2741
I am working on a view based app, I have set the background image as follows.
.h file:
UIImageView *BackgroundImage;
.m file:
viewdidLoad method:
BackgroundImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"BG.png"]];
[[self view] addSubview:BackgroundImage];
[BackgroundImage.superview sendSubviewToBack:BackgroundImage];
and on the rotate method:
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
BackgroundImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"BG2.png"]];
[[self view] addSubview:BackgroundImage];
[BackgroundImage.superview sendSubviewToBack:BackgroundImage];
[super viewDidLoad];
}
Using this code I am able to set the background, but on rotation the first loaded image is not removed and the second one is loading just behind the first one, so just half of the image is visible, because of the first image is in front of second one.
Is there is a better way to do this?
OR
How can I just remove the first image and then set the second one?
Please help me to resolve this.
Upvotes: 1
Views: 750
Reputation: 81856
Just set the new image when rotating:
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
BackgroundImage.image = [UIImage imageNamed:@"BG2.png"];
}
Your code kept adding new image views when rotating.
How [do stuff] properly in iOS?
_backgroundImage
instead of BackgroundImage
.[self.view insertSubview:_backgroundImage atIndex:0];
Upvotes: 0
Reputation: 2369
If you change your code like this should to work
BackgroundImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"BG.png"]];
[self.view addSubview:BackgroundImage];
[self.view sendSubviewToBack:BackgroundImage];
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
[BackgroundImage removeFromSuperview];
BackgroundImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"BG2.png"]];
[self.view addSubview:BackgroundImage];
[self.view sendSubviewToBack:BackgroundImage];
[super viewDidLoad];
}
Upvotes: 1
Reputation: 3399
This is because you are initializing the UIImageview again. Better to use same UIImageView that is backgroundImage with different image.
[Background Image set image:[UIImage imageNamed:@"BG2.png"]];
Upvotes: 0
Reputation: 7924
Change your didRotate... method to:
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
[BackgroundImage removeFromSuperview];
BackgroundImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"BG2.png"]];
[[self view] addSubview:BackgroundImage];
}
Notice the [BackgroundImage removeFromSuperview]; line. What we are doing here is whenever the device rotates, you remove the old image view and add another one.
Also please notice that variable names should start with lower case, so BackgroundImage should be backgroundImage. This is to tell them apart from classes' names.
Upvotes: 2