Clint Whaley
Clint Whaley

Reputation: 469

Button position different for different iphone

How can i get the buttons to stay on the same position for all different versions of the iphone? I have a background image and on top of that, i have a button. This is for iPhone 6.

This one is for iphone 5.

Is there anyway i can provide a fixed position for the button?

The following is what it is supposed to look like, based on the story board. enter image description here

Upvotes: 1

Views: 1014

Answers (1)

rob mayoff
rob mayoff

Reputation: 385530

All iOS devices with 4", 4.7", and 5.5" screens (which is all iPhones since the iPhone 5 and all iPods since the 5th generation) have the same screen aspect ratio, 16:9, so if those are the target devices, this is doable with constraints in the storyboard and no code.

You posted an iPhone 6-sized screen shot. (Pro tip: press ⌘S in the simulator to save a screen shot to your desktop so you don't have to try to crop it by hand.) In this shot, you've put the bottom edge of the button about 300 pixels = 150 points above the bottom edge of the screen. The screen of an iPhone 6 is 667 points tall.

So step one is to add a “spacer” view to your root view. Set its background color to something you can see, and make it hidden. (Hidden views still participate in layout.) Pin the spacer to the left and bottom edges of the root view. Make it 20 points wide. The width doesn't really matter. Create an equal-height constraint between the spacer and the root view. Then edit the equal-height constraint. Set the multiplier to 150:667 (use that string and Xcode will do the division for you). Here's what it should look like:

spacer configured

Now constrain the bottom edge of your button to equal the top edge of the spacer:

button bottom constraint

We can see how the button is placed on different screen sizes using the Preview mode in the Assistant Editor:

previews

As requested, the button is “always on top of the blurred yellow line”.

If you also want to support 3.5 inch screens and you set the mode of the background image view to “Aspect Fit” (which will leave blank space on the sides of the image) or “Scale To Fill” (which will squash the image a little bit), then this layout will work as-is.

If you also want to support 3.5 inch screens and you use a differently-cropped background image (e.g. you use mode “Aspect Fill”), you will need to replace the spacer's height constraint in code based on the screen size of the device.

Upvotes: 5

Related Questions