Applying a pattern is something that you already know. But supporting the older 3.5 inch iPhones and the iPhone 5’s taller resolution means, shipping two sets of background images and choosing the right one depending on the device.
However, there are at least two drawbacks of the above mentioned method. Firstly, shipping multiple images means you are increasing the download size of your app. Default.png and Background.png are usually the biggest files in most applications and adding another background for iPhone 5 is a felony. Secondly, code switch based on device is something I would not recommend writing explicitly, especially, if there is a way around, use it.

I instead recommend colorWithPatternImage: and I’m going to show you how I do this.

Step 1: Subclass UIViewController and create your own. I recommend this to avoid code duplication. In the viewDidLoad method, create a pattern layer and add it as a sublayer of your view. You should strongly own the pattern layer.

- (void)viewDidLoad
{
[super viewDidLoad];
 
self.patternLayer = [CALayer layer];
self.patternLayer.frame = self.view.bounds;
self.patternLayer.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"BackgroundPattern"]].CGColor;
self.patternLayer.opacity = 1.0f;
[self.view.layer insertSublayer:self.patternLayer atIndex:0];
}

Step 2: In your viewWillLayoutSubviews method, adjust the pattern layer’s frame. This is for iPhone 5 compatibility.

- (void)viewWillLayoutSubviews {
 
self.patternLayer.frame = self.view.bounds;
[super viewWillLayoutSubviews];
}

That’s all. Any view that is inheriting from this subclass of UIViewController will automatically get the background pattern. You can go on and apply corner radius, drop shadows and play around here to apply themes globally.


Mugunth

Follow me on Twitter

  • Guest

    Sorry, but I don’t get the point…
    Why don’t you just use the following?
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@”BackgroundPatern”]];

  • Nikita

    Hi.
    Why you do this twice
    self.patternLayer.frame = self.view.bounds;
    in viewDidLoad viewDidLoad and in viewWillLayoutSubviews?

  • delete me

    • MugunthKumar

      You usually do a bit more with that layer like adding a corner radius and a shadow.

  • I agree with Guest.  Seems like a lot of extra just when you can set the self.view.backgroundColor property to your pattern image color, no?