Search code examples
iosswiftautolayout

Relative Center in Autolayout


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:

  • Adding top & bottom Constraint for 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.


Solution

  • 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