Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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.

like image 765
xiaowoo Avatar asked Aug 14 '14 06:08

xiaowoo


1 Answers

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 previewUIView constraint setup

like image 172
Mike S Avatar answered Nov 01 '22 19:11

Mike S