Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Setting centerXAnchor constraint with multiplier programmatically doesn't work

I am trying to set a horizontal center constraint of a view with multiplier programmatically. But what I get is always a constraint with 1.0 as the multiplier. This is what I did:

private func createHalfCenteredView() {
    let newView = UIView(frame: .zero)
    newView.backgroundColor = .systemTeal
    view.addSubview(newView)
    
    newView.translatesAutoresizingMaskIntoConstraints = false
    let top = newView.topAnchor.constraint(equalTo: view.topAnchor)
    let bottom = newView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
    let width = newView.widthAnchor.constraint(equalToConstant: 100)
    let center = newView.centerXAnchor.constraint(equalToSystemSpacingAfter: view.centerXAnchor,
                                                  multiplier: 0.5)
    
    NSLayoutConstraint.activate([top, bottom, width, center])
    
    newView.setNeedsUpdateConstraints()
    view.setNeedsLayout()
    view.layoutIfNeeded()
}

I tried using lessThanOrEqualToSystemSpacingAfter instead of equalToSystemSpacingAfter but it is still the same. The multiplier is always 1.0 or exactly in the middle.

Can anybody help me with this? Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can’t use multipliers using helpers functions, try this way

 let center = NSLayoutConstraint(item: newView, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 0.5, constant: 0)

Refer to answer

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading