如何通过乘数以编程方式添加约束中心

问题描述 投票:0回答:1

我确实在情节提要中使用具有中心约束的乘法器,现在我想通过编程方式进行同样的操作,但不知道如何操作。

[否,this thread没有帮助,因为可接受的答案是一种解决方法,如果以后超级视图大小发生更改,它将无法自动调整大小。

情节提要板中心X约束:

enter image description here

我尝试的没有成功的内容:

// Does not exist
buttonLeft.centerXAnchor.constraint(equalTo: centerXAnchor, multiplier: 0.5).isActivate = true

// error shown:
// Cannot convert value of type 'NSLayoutXAxisAnchor' to expected argument type 'NSLayoutConstraint.Attribute'
let newConstraint = NSLayoutConstraint(item: self, attribute: centerXAnchor, relatedBy: .equal, toItem: buttonLeft, attribute: centerXAnchor, multiplier: 0.5, constant: 0)

有可能吗?

  • 是:如何?
  • 否:您对为什么不能以编程方式进行解释吗?这东西是语法上的糖掩盖了更复杂的东西吗?我迷路了。

是的,使用情节提要设置此约束时,它可以按预期工作

ios swift autolayout nslayoutconstraint programmatically
1个回答
0
投票

所以有可能,我误用了centerXAnchor而不是使用.centerX

而且我打电话给每个物品的顺序也不正确:

// Not Working
NSLayoutConstraint(item: self, attribute: centerXAnchor, relatedBy: .equal, toItem: buttonLeft, attribute: centerXAnchor, multiplier: 0.5, constant: 0)

// Working
NSLayoutConstraint(item: buttonLeft, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 0.5, constant: 0)

尽管我找不到使用anchors方法创建约束的任何方法。

© www.soinside.com 2019 - 2024. All rights reserved.