Setting background image programmatically in Xib

I have an XIB file with UIControl and UIScrollView elements inside it. I would like to add a background image to the view. I tried to add ImageView to IB, but I could not get it to be present as a background, and it hid the controls. Sending a sendViewBack message sendViewBack nothing either.

When I create the UIImageView program code, it is not displayed.

Below is the code I tried:

Software Creation

 UIImage *imageBackground = [UIImage imageWithContentsOfFile:@"globalbackground"]; UIImageView *backgroundView = [[UIImageView alloc] initWithImage:imageBackground]; [[self view] addSubview:backgroundView]; [[self view] sendSubviewToBack:backgroundView]; 

Work with the NIB file

 [[self view] sendSubviewToBack:background]; 

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

Is there any step I'm missing here?

+6
source share
2 answers

Install the frame and do not use sendSubviewToBack: If you are working with UIImageViews, you should 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 it was a bargain.

+8
source
  • Do not add the image view as a subview of the scroll, it should be a separate view at the top of the hierarchy, and then sent to the back of the Z-order.
  • You will need to set the background of your scroll view to [UIColor clearColor] and make sure that the scroll is not marked as opaque. You can do this in code or in the interface builder.
  • Do not use imageWithContentsOfFile , and then just pass it the file name without the extension (I assume .png) - this will probably return nil . Use imageNamed: (you do not provide an extension in this case, iOS4 or later).

Depending on the nature of your image, you can also generate a color with it and use it as the background color of your scroll view. I assume self.view is a scroll view:

 self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"globalBackground"]]; 
+5
source

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


All Articles