【问题标题】:Cannot convert value of type '[NSLayoutConstraint]' error in swift 2在 swift 2 中无法转换类型“[NSLayoutConstraint]”错误的值
【发布时间】:2016-08-09 09:15:40
【问题描述】:
我想通过添加这行代码来为UIImageView添加约束:
addConstraint(NSLayoutConstraint.constraintsWithVisualFormat("H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": userProfileImageView]))
但是 xcode 显示这个错误:
我该如何解决这个错误?
【问题讨论】:
标签:
ios
swift
swift2
nslayoutconstraint
【解决方案1】:
使用addConstraints,而不是addConstraint。
constraintsWithVisualFormat 返回一个数组。
你的代码变成:
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[v0]|", options: [], metrics: nil, views: ["v0": userProfileImageView])
【解决方案2】:
let horizontalprofileViewConstraint = NSLayoutConstraint.constraintsWithVisualFormat("H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": userProfileImageView]
如果您单击选项并将鼠标悬停在 horizontalprofileViewConstraint 上,您将看到其类型为 [NSLayoutConstraint],这已经是一个数组。
所以你可以做的是:
view.addConstraints(horizontalprofileViewConstraint)
如果您有多个视图,那么您可以这样做:
view.addConstraints(horizontalprofileViewConstraint + verticalprofileViewConstraint)
+ 为您加入数组。