以编程方式设置中心XAnchor约束不起作用



我正试图通过编程设置具有乘数的视图的水平中心约束。但我得到的总是一个以1.0为乘数的约束。这就是我所做的:

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()
}

我尝试使用lessThanOrEqualToSystemSpacingAfter而不是equalToSystemSpacingAfter,但它仍然是一样的。乘数总是1.0或正好在中间。

有人能帮我吗?谢谢

您不能使用helper函数来使用乘法器,请尝试这种方法

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

参考答案

最新更新