Mohammad Sadiq
Mohammad Sadiq

Reputation: 5241

iOS Autolayout : Give top space equal to 1/5 of superview height

I want to set top space of my label to 1/5 of super view height. I know we can do this at runtime by changing the constant to 1/5 of super view. But I want to do this using XIB only. Is there any way to achieve this?

Upvotes: 0

Views: 727

Answers (3)

Dan Rosenstark
Dan Rosenstark

Reputation: 69757

Programatic version of accepted answer is something like

let spacerFromTop = UILayoutGuide()
superview.addLayoutGuide(spacerFromTop)
spacerFromTop.topAnchor.constraint(equalTo: superview.topAnchor).isActive = true
spacerFromTop.heightAnchor.constraint(equalTo: superview.heightAnchor, multiplier: 0.8).isActive = true

button.topAnchor.constraint(equalTo: spacerFromTop.bottomAnchor).isActive = true

Where button is the thing I want 80% from top and superview is the, um, superview. Use 0.2 for 1/5, of course.

Upvotes: 0

Horst
Horst

Reputation: 1739

A complicated way is to calculate the align to vertical center enter image description here

128 = (600 - 20) * 0.2 so we set 0.6 to the multiplier

Upvotes: 2

Himanshu jamnani
Himanshu jamnani

Reputation: 326

Indeed @EI Captain,

We need to use spacer view. @Mohammad, please have a look at constraints I have given to space view and label. it will definitely solve your issue.

Attaching screen shot for you! enjoy.

SpacerView

Your Label

Upvotes: 4

Related Questions