How to make uiview's width fit to the width of the parent view with some padding for both iphone and ipad using universal storyboard in xcode 6?

xiaowoo picture xiaowoo · Aug 14, 2014 · Viewed 25k times · Source

I am learning constraints and Universal Storyboard in xcode 6 and having a little bit of difficulty here.

Using Universal Storyboard, my goal is to create a UIView that fits perfectly on an iPad Simulator(768 x 1024) and iPhone 4 Simulator(_ x _) with lets say 50 pixel padding or margin on the left and right side.

Goal should look like this:

enter image description here

I am using Universal Storyboard and auto layout and I am getting the following result on the preview enter image description here

What I have done so far is just drag in a UIView into the Universal Storyboard editor, and then give it a width(768) that fills the iPad Screen, and then applied a width = 768, height = 200 constraints and a constraint to center horizontally and constraint to center vertically.

Observe result:

IPad screen fills width perfectly. However a closer look at my iPhone screen(Image 1), the UIView(in green)'s width do not fill to parent(its width is much bigger than its parent width)

Questions:

Problem 1) Is there a way to use Universal Storyboard to create a UIView that fills its width to its parent UIView both on the iPad and iPhone?

Problem 2) If problem 1 is achievable, then how do you add a padding or margin left and right to the green UIView?

thanks, and would appreciate any suggestions, comments, or opinions.

Answer

Mike S picture Mike S · Aug 14, 2014

Instead of using a width constraint, you want to be looking at Leading Space and Trailing Space constraints.

You'll want to add a Leading Space constraint from your green UIView to its superview and set that constraint's constant to the margin you want (50), and then do the same for Trailing Space. You should keep your height and center vertically constraints as is, but you can delete your center horizontally constraint since the Trailing Space and Leading Space constraints will handle centering your view already.

It should end up looking something like this:

constraint layout and preview UIView constraint setup