Search code examples
iosswiftconstraintsnslayoutanchor

Add multiplier to NSLayoutAnchor constraints in Swift


Anchor constraints simplify adding constraints but the multiplier property available in storyboard does not seem to be available for all types of constraints.

For example, as per the answer here, you can center a label in a view with:

view.addSubview(loadingLabel)
loadingLabel.translatesAutoresizingMaskIntoConstraints = false 
loadingLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
loadingLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

However, apparently, while you can set the multiplier for length constraints as in:

someView.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.4)

You cannot add a similar parameter to the CenterX or CenterY parameter, possibly because Apple doesn't think that makes sense for a point, although you can do this in Storyboard as discussed in this question.

What is the best way to add a multiplier to the constraints for centering a point in order to make the point a proportion of the screen size from the top?


Solution

  • You can't add multipliers to the anchor methods for X and Y axis constraint, they are only available for the dimensional anchors. But, the NSLayoutContraint has an option for setting the multiplier. So for example, if you want to set the label in the middle of the top and centre of the super view along the Y axis here's how you do this:

    view.addSubview(loadingLabel)
    loadingLabel.translatesAutoresizingMaskIntoConstraints = false 
    loadingLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    NSLayoutConstraint(item: loadingLabel, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 0.5, constant: 0).isActive = true