Constrain UIView's proportionally

91 Views Asked by At

I want to position my view's in relative terms. I want do use percentages and not pixels. Say I want to position a button's center at 25% of its super view's height. How would I do this?

One way to do it would be:

button.topAnchor.constraint( equalTo: superView.topAnchor, constant: /* compute constant "dynamically") .isActive = true

But this feels silly because we have a multiplier parameter in many of the Layout Margin API functions.

But yet if I type button.centerYAnchor.constraint, none of the suggested completions show any functions that take a multiplier argument except for one's with systemSpacing in the name. I've looked into "system spacing" but cannot figure out what it does.

If I have this constraint:

button.topAnchor.constraintEqualToSystemSpacingBelow(rootView.topAnchor, multiplier: 0.2).isActive = true

The view is just position directly under its superView's top.

1

There are 1 best solutions below

0
On

I haven't found a way to do it with the layout anchors, but here is how to do it by creating the NSLayoutConstraint directly:

NSLayoutConstraint(item: button, attribute: .centerY,
    relatedBy: .equal, toItem: superView, attribute: .bottom,
    multiplier: 0.25, constant: 0).isActive = true