Setting Background Image Programmatically In A Xib

Andrew Lauer Barinov picture Andrew Lauer Barinov · Jan 4, 2012 · Viewed 11k times · Source

I have a XIB file with UIControl and UIScrollView elements inside of it. I would like to add a background image to the view. I tried adding an ImageView in IB but I could not get it to be present as a background and it obscured the control elements. Sending a sendViewBack message doesn't seem to do anything either.

When I create a UIImageView programmatically, it doesn't show up.

Below is the code I attempted:

Programmatic Creation

UIImage *imageBackground = [UIImage imageWithContentsOfFile:@"globalbackground"];

UIImageView *backgroundView = [[UIImageView alloc] initWithImage:imageBackground];

[[self view] addSubview:backgroundView];

[[self view] sendSubviewToBack:backgroundView];

Dealing with the NIB file

[[self view] sendSubviewToBack:background];

where background is an IBOutlet declared in the header file and connected to the NIB's image view in IB.

Is there a step I'm missing here?

Answer

pmk picture pmk · Jan 4, 2012

Set the frame and dont use sendSubviewToBack:. If you are working with UIImageViews you have to use [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"imageName.png"]];

UIImageView *backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"imageBackground"]];
backgroundView.frame = self.view.bounds;
[[self view] addSubview:backgroundView];

hope this was the deal.