SaRaVaNaN DM
SaRaVaNaN DM

Reputation: 4410

iOS Auto layout in percentage

I wanna create a simple iOS application using autolayout that displays three UIViews. One on the top, one on the left and the other on the right. The top view should be 50 pixels high and fills the horizontal space completely. The left column should fill 40% of the horizontal space and should fill 100% of the vertical space. The right column should be 60% of the horizontal space and 100% of the vertical space. Finally in the left UIView wanna add a single button.

Upvotes: 0

Views: 2821

Answers (3)

Mark Gerrior
Mark Gerrior

Reputation: 387

The two existing answers didn't work for me. My answer was built using Xcode version 10.1 (10B61).

The core question is "How Can I Set a View’s Width to be a Percentage in a Storyboard". Answer: the view's width needs to be associated with the superview.

Explanation:

  1. In the Main.storyboard (already containing a View Controller and a View), add a View. I’m going to call it YellowView). And change its containing view name to SuperView.
  2. In the YellowView's Attributes Inspector change the Background to Yellow.
  3. Click on New Constraints and Top = 0, Leading (left) = 0, height = 50
  4. Control Drag from the YellowView to the Superview and let go, in the resulting dialog select "Equal Widths" Figure 1 Note: YellowView's width becomes the width of the SuperView.
  5. In the Storyboard, Double-click the width constraint we just added and change the Multiplier to 0.25 (Note: Typing .25 will not work - the leading zero is necessary)

Upvotes: 4

Ketan Parmar
Ketan Parmar

Reputation: 27448

Your constraints should be like,

first view - top,leading(left),trailing(right) and fix height

left view - top, left(leading), bottom and equal width with superview with multiplier 0.4 (or width constraint with 0.4 multiplier)

right view - top,right(trailing),bottom and equal width with superview with multiplier 0.6 (or width constraint with 0.6 multiplier)

hope this will help :)

Upvotes: 2

BrikerMan
BrikerMan

Reputation: 334

Yes, You can.

  1. Add first view at the top, add four constraint, top 0 left 0 right 0 and height 50. enter image description here
  2. Add second view at bottom of first view, make it top 0 left 0 heigth 100.
  3. Here is the trick, choose first and secound view, then make them equal width.
  4. Choose secound view's width constraint, and change the multiplier to 0.4. enter image description here

Upvotes: 6

Related Questions