Home > Mobile >  Setting centerXAnchor constraint with multiplier programmatically doesn't work
Setting centerXAnchor constraint with multiplier programmatically doesn't work

Time:03-04

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.

CodePudding user response:

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

  • Related