Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use auto layout to start a view in the half of its superview?

I have a view inside a view:

+--------------+
|              |
|       +-----+|
|       |     ||
|       +-----+|
+--------------+

I’d like the inner view to always start right in the middle of the outer view horizontally, and span the whole remaining half to the right edge:

innerView.frame.size.width = outerView.frame.size.width/2;
innerView.frame.origin.x = outerView.frame.size.width/2;

How can I express that using auto layout?

like image 231
zoul Avatar asked Jan 08 '13 09:01

zoul


People also ask

What is a stack view?

Stack views let you leverage the power of Auto Layout, creating user interfaces that can dynamically adapt to the device's orientation, screen size, and any changes in the available space. The stack view manages the layout of all the views in its arrangedSubviews property.

What are two properties that auto layout constraints control on a Uiview?

Auto Layout defines margins for each view. These margins describe the preferred spacing between the edge of the view and its subviews. You can access the view's margins using either the layoutMargins or layoutMarginsGuide property.

How does a view's intrinsic content size aid in auto layout?

In general, the intrinsic content size simplifies the layout, reducing the number of constraints you need. However, using the intrinsic content size often requires setting the view's content-hugging and compression-resistance (CHCR) priorities, which can add additional complications.


1 Answers

You actually can do this in IB/Storyboards as far back as Xcode 5.1 (potentially earlier)

  1. Create a width constraint between the view and the super view
  2. Set it's relationship to "Equal"
  3. Set it's constant to "0"
  4. Set it's multiplier to "2:1" or "1:2" (depending on item order in the constraint)

IB, apparently, only allows multipliers to be set to integers or ratios, not floating point numbers. Here's a screen cap for more clarity

Constraint setting for width half it's parent

Note: if "First Item" and "Second Item" are flipped, the ratio is "2:1"

like image 132
Adam Ritenauer Avatar answered Sep 25 '22 06:09

Adam Ritenauer