Reputation: 483
I am using Autolayout to position my Views.
In my case, that is a UILabel
on top and a UIStackView
below it.
The UIStackView
is configured for .fill
and all it's arrangedSubviews
have a correct heightConstraint
.
What I want to do is add Constraints so that the UIStackView
is vertically centred in the space between myLabel.bottomAnchor
& mySuperview.bottomAnchor
.
What I tried so far is:
UIStackView
:
_stackView.topAnchor.constraint(greaterThanOrEqualTo: _myLabel.bottomAnchor)
_stackView.bottomAnchor.constraint(greaterThanOrEqualTo: _mySuperview.bottomAnchor)
Now this works in that it just puts the correctly sized UIStackView
at the bottom of _mySuperview
.
What I want however is it to be in the centre.
I saw there is a method called anchorWithOffset(to:)
which sounds like exactly what I need but could not find the correct way to use it.
So my question is, how do I centre a UIView
between two given NSLayoutAnchors
?
Edit: I am aware of the fact that I could just add a UIView
that is constraint between my two other views and centre my UIStackView
in there. I am however looking for a purer solution.
Upvotes: 4
Views: 1054
Reputation: 1675
Next code does the trick:
let dimensionBefore = _myLabel.bottomAnchor.anchorWithOffset(to: _stackView.centerYAnchor)
let dimensionAfter = _stackView.centerYAnchor.anchorWithOffset(to: _mySuperview.bottomAnchor)
dimensionBefore.constraint(equalTo: dimensionAfter, multiplier: 1).isActive = true
But this works only since iOS 10
Upvotes: 8
Reputation: 53092
It looks like you want to achieve this in code rather than in storyboard/xib, but these are often really useful to test out autolayout ideas - once you've got it working in a storyboard it'll then be clear what code you need to write to do the same.
You could achieve this by using an additional vertical UIStackView
to wrap the UIStackView
that you want.
In the example below, I added empty UIView
s above and below the inner UIStackView
, and set the outer one to Fit Proportionally
Alternatively…
Upvotes: 1