我有以下代码来尝试创建一个约束数组以添加到 View 中:
let views = ["button": button]
let metrics = ["margin": 16]
var constraints: [AnyObject] = []
constraints += NSLayoutConstraint.constraintsWithVisualFormat("|-margin-[button]-margin-|", options: 0, metrics: metrics, views: views)
根据我对 Swift 数组的理解,我应该能够将它们“+=”在一起以连接两者,但我收到一个错误:
"Binary operator '+=' cannot be applied to two [AnyObject] operands"
这段代码有什么问题?
最佳答案
这不是因为运营商。
这是因为您传递的是 Int,实际上应该传递 NSLayoutFormatOptions
枚举类型。
如果您为 options
参数传入 NSLayoutFormatOptions
枚举之一,错误将会消失:
constraints += NSLayoutConstraint.constraintsWithVisualFormat("|-margin-[button]-margin-|", options: .AlignAllLeft, metrics: metrics, views: views)
或者您也可以使用您想要使用的 Int 值初始化 NSLayoutFormatOptions
,如下所示:
NSLayoutFormatOptions(rawValue: 0)
0 在 Objective-C 中可以工作,但你需要在 Swift 中使用实际的枚举值。 在许多情况下,Swift 错误仍然经常具有误导性,就像这个例子。
希望这有帮助。
关于xcode - “+=”不能应用于两个 [AnyObject] 操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30762779/