我想在很多项目上与CenterX对齐。

此代码适用于1个项目:

let control_constraint_ItemAlign = NSLayoutConstraint(item: emailField, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)

但我想尝试这样的代码:
let control_constraint_ItemAlign =
NSLayoutConstraint(item:[emailField,passwordField,loginButton],
 attribute: NSLayoutAttribute.CenterX,
 relatedBy: NSLayoutRelation.Equal,
 toItem: self.view,
 attribute: NSLayoutAttribute.CenterX,
 multiplier: 1,
 constant: 0)

还是唯一的解决方案是为每个项目写一个约束?

最佳答案

您可以遍历视图:

for view in [emailField,passwordField,loginButton] {
    let control_constraint_ItemAlign =
    NSLayoutConstraint(item:view,
     attribute: NSLayoutAttribute.CenterX,
     relatedBy: NSLayoutRelation.Equal,
     toItem: self.view,
     attribute: NSLayoutAttribute.CenterX,
     multiplier: 1,
     constant: 0)
    self.view.addConstraint(control_constraint_ItemAlign)
}

或者,您可以将适当的选项传递给视觉格式语言

09-27 04:59