Search code examples
iosobjective-ciphonealignmentuistoryboard

Centering Objects From Storyboard


Im starting to experiment with storyboard. As you can see I have chosen the storyboard size to be height=regular and width=compact, which says “For all iPhones in portrait”.

Aligned view in storyboard

The simulator I am using is iPhone6 however when I run everything is slightly off to the right.

enter image description here

Can someone explain what is happening or what I am missing?


Solution

  • The problem is that (as described in the comments) you are positioning the views without AutoLayout. When you just drag and drop the views, it's actually setting the frame's positions and sizes. The main problem with this approach is that it doesn't set the position and size in a proportional and related manner, taking in consideration the container. This is why you're getting the view at the current position. If you run in another simulator, maybe you can get the correct position, or maybe not. What you can do to change this is apply auto layout constraints to those views. There's a special constraint to center views horizontally. With autoLayout you can go further, specifying relation between one or more views, and those views not necessarily need have the same container view.

    One quick example:

    Adding center constraints to parent view

    View related information on the right: you can see you constraints there![][2]

    Notes:

    I'm using universal storyboard to take those screenshots. It's more flexible and with AL you don't necessarily have to concern yourself with the size, as views adjust themselves depending on the constraints applied to.

    EDIT:

    https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/Introduction/Introduction.html

    This is a link to auto layout guide provided by apple, a great tutorial on how to get your hands dirty in this little world.