Use one background image programatically for both iPhone4 and iPhone5 with NSLayoutConstraint

StackOverflow https://stackoverflow.com/questions/22536213

  •  18-06-2023
  •  | 
  •  

Question

I'm trying to avoid detecting whether I'm on iPhone 4 or 5 screen size by using NSLayoutConstraint. This is my code:

UIImageView *backgroundImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Flow-02"]];
[self.view addSubview:backgroundImage];
[self.view sendSubviewToBack:backgroundImage];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[backgroundImage]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(backgroundImage)]];

but it doesn't work.

My Flow-02 image has a resolution of 640x1136, so I was thinking this would make it fit the screen, but it doesn't. Is there a way to do it?

EDIT: Following rmaddy's answer below I added the line that sets the image's frame like this:

backgroundImage.frame = self.view.bounds;

It does set my image correctly on the iPhone 5 simulator, but on my iPhone 4s it's still stretched sideways.

Neither the autoresizingMask approach, nor the setting of V and H to the constraintsWithVisualFormat, suggested by Anindya Sengupta, have any effect.

Was it helpful?

Solution

Another option would be something like this:

UIImageView *backgroundImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Flow-02"]];
backgroundImage.contentMode = UIViewContentModeScaleToFill;
backgroundImage.frame = self.view.bounds;
backgroundImage.autoResizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[self.view addSubview:backgroundImage];
[self.view sendSubviewToBack:backgroundImage];

Keep in mind that either approach is only a good idea of the image looks OK when scaled as needed.

OTHER TIPS

The problem is in the Visual Format you are setting.

[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[backgroundImage]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(backgroundImage)]];

The above code it pinning the backgroundImage to the left and right side of the container. But the iPhone is not getting fat, right? So, lets do this additionally

[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[backgroundImage]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(backgroundImage)]];

I just added V: which will tell the compiler to consider it vertically. For Horizontal it would have been H: If you don't mention anything, by default it is "Horizontal" but it is a good practice to mention it always to make the code more understandable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top