Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Background Image Programmatically In A Xib

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?

like image 328
Andrew Lauer Barinov Avatar asked Jan 04 '12 08:01

Andrew Lauer Barinov


2 Answers

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.

like image 198
pmk Avatar answered Nov 18 '22 11:11

pmk


  • Don't add the image view as a subview of the scroll view, it needs to be a separate view at the top level of the hierarchy, then sent to the back of the Z-order.
  • You will need to set the background of your scroll view to [UIColor clearColor], and ensure that the scroll view is not marked as opaque. You can do this in code or in interface builder.
  • Don't use imageWithContentsOfFile and then just pass it a filename with no extension (I'm assuming .png) - this is probably returning nil. Use imageNamed: instead (you don't supply an extension in that case, iOS4 and above)

Depending on the nature of your image, you can also generate a colour with it and use that as the background colour of your scroll view. I'm assuming self.view is the scroll view:

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"globalBackground"]];
like image 34
jrturton Avatar answered Nov 18 '22 12:11

jrturton