简体   繁体   English

以编程方式使用乘数设置 centerXAnchor 约束不起作用

[英]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.但我得到的始终是一个以1.0作为乘数的约束。 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.我尝试使用lessThanOrEqualToSystemSpacingAfter而不是equalToSystemSpacingAfter但它仍然是一样的。 The multiplier is always 1.0 or exactly in the middle.乘数始终为 1.0 或恰好在中间。

Can anybody help me with this?有人可以帮我吗? Thanks.谢谢。

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参考答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM