Swift:无效参数不满足:约束

时间:2014-08-26 13:22:18

标签: ios objective-c xcode swift nslayoutconstraint

我收到错误:

  

无效参数不满足:[约束isKindOfClass:[NSLayoutConstraint class]]

我的自动布局约束代码用Swift编写:

    let d:NSDictionary = ["scrollView": scrollView]
    let hc:NSArray = [NSLayoutConstraint.constraintsWithVisualFormat("H:|[scrollView]|", options: NSLayoutFormatOptions.allZeros, metrics: nil, views: d)]
    let vc:NSArray = [NSLayoutConstraint.constraintsWithVisualFormat("V:|[scrollView]|", options: NSLayoutFormatOptions.allZeros, metrics: nil, views: d)]
    view.addConstraints(hc)
    view.addConstraints(vc)

有没有人知道这个错误试图告诉我什么?据我所知,该参数的类型为NSArray,其中包含NSLayoutConstraint个对象。我怀疑我必须明确地将数组定义为NSArray,但是没有解决它。

1 个答案:

答案 0 :(得分:20)

NSLayoutConstraint.constraintsWithVisualFormat已经返回NSArray,因此您无需将其包装在另一个数组中。所以试试:

let d:NSDictionary = ["scrollView": scrollView]
let hc:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:|[scrollView]|", options: NSLayoutFormatOptions.allZeros, metrics: nil, views: d)
let vc:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:|[scrollView]|", options: NSLayoutFormatOptions.allZeros, metrics: nil, views: d)
view.addConstraints(hc)
view.addConstraints(vc)