18

Is there a way to set same background image for all views?

Setting same background in all viewDidLoad: methods. It's not cool.

Dinesh Raja
  • 8,501
  • 5
  • 42
  • 81
andrusha
  • 183
  • 1
  • 4
  • It's only one line of code, just copy and paste. How many views do you have? – woz Nov 15 '12 at 13:36
  • Loop through all subviews and apply the background is the only way I can think of. – chrislhardin Nov 15 '12 at 13:36
  • are you sure you don't want to set their background color to transparent and set the color once for the container view? – nonopolarity Nov 15 '12 at 13:38
  • Now you have some options. If you are not satisfied, make an abstract subclass with red background, and let all the vcs inherit from that object. – Martol1ni Nov 15 '12 at 13:41

4 Answers4

11

You can create a custom class, let's call it a TemplateView, which is subclass of UIView. Then using xib/storyboards select the controller view and identity inspector change the Class property to 'TemplateView'.

Subsequently using an UIAppearance change the background color of the template view to the desired one.

 [[TemplateView appearance]setBackgroundColor:[UIColor blueColor]];

That will change the background color of each of the template views in your project. I think it's better solution than

[[UIView appearance] setBackgroundColor:[UIColor redColor]];

because we don't change the background of everything, just our custom class. Hope it will help.

Janusz Chudzynski
  • 2,700
  • 3
  • 33
  • 46
  • 2
    This is a much better answer than the accepted answer. Giving all the UIViews a background will produce many unexpected side-effects. – Stijn Mar 25 '16 at 14:50
2

Yes, using UIAppearance in iOS5+:

[[UIView appearance] setBackgroundColor:[UIColor redColor]];

NOTE: UIView conforms to <UIAppearance, UIAppearanceContainer> protocols but does not mark any properties as UI_APPEARANCE_SELECTOR for some reason.

Cfr
  • 5,092
  • 1
  • 33
  • 50
  • 19
    true, but this will set the background for all subviews that subclass UIView (almost everything) including Buttons, Labels etc. ... – jimpic Apr 18 '13 at 16:08
0

I don't think this is a good idea, but if you really want to do this, you could do something like this:

- (void)setBGColor:(UIColor *)color forAllSubviewsOf:(UIView *)view
{
    [view setBackgroundColor:color];
    for (UIView *sub in view.subviews)
        [self setBGColor:color forAllSubviewsOf:sub];
}
jimpic
  • 5,360
  • 2
  • 28
  • 37
0

I guess you can use Method Swizzling kind some feature to change all views colour or image setting.

Check following

https://wiredcraft.com/blog/method-swizzling-ios/