Siyuan Ren
Siyuan Ren

Reputation: 7844

Auto layout: constraint that involves multiple items

For example, I want a certain text field to be placed below the navigation bar with a distance equal to a quarter of the total height of the superview. This involves three items: the text field, the top layout guide, and the superview. How can one create such constraint, either in Interface Builder or by programming?

Upvotes: 2

Views: 230

Answers (3)

dudeman
dudeman

Reputation: 1136

The way I would do it is using constraintsWithVisualFormat. Like so:

double quarterSuperViewHeight = superView.frame.size.height / 4;
NSDictionary* metrics = NSDictionaryOfVariableBindings(quarterSuperViewHeight);
NSDictionary* views = NSDictionaryOfVariableBindings(textField, navigationBar);
[superView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[navigationBar]-quarterSuperViewHeight-[textField]" options:0 metrics:metrics: views:views];

This should set the space between the navigation bar and the text field to a quarter of the superview's height. Now I can't quite remember if you'll have to redo this layout everytime the device rotates, but I don't think you should.

Upvotes: 0

GaétanZ
GaétanZ

Reputation: 4930

Every time you need something like this, and don't want to use the Benjamin's technique, use the multiplier property of an equal width or height constraint to the superview.

Upvotes: 0

Mats
Mats

Reputation: 8638

It is not possible to do with one constraint. Instead you need to create an extra UIView above the text field. Then you can set the following contraints:

  1. 4 * extraView.height = containerView.height
  2. extraView.top = topLayoutGuide
  3. extraView.bottom = textField.top

Upvotes: 1

Related Questions