Search code examples
swiftconstraintsios-autolayout

Cannot convert value of type '[NSLayoutConstraint]' to expected argument type 'NSLayoutConstraint'


I am using Xcode 9 beta 5 .I pragmatically added the contrarian

addConstraint(NSLayoutConstraint.constraints(withVisualFormat: "H: |-16-[v0]-16-|" , options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":thumbnailImageView]))

addConstraint(NSLayoutConstraint.constraints(withVisualFormat: "V: |-16-[v0]-16-|" , options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":thumbnailImageView]))

I am getting error:

Cannot convert value of type '[NSLayoutConstraint]' to expected argument type 'NSLayoutConstraint'

Error Image

Screen Shot

How to remove this error?


Solution

  • The problem is that NSLayoutConstraint.constraints(withVisualFormat:options:metrics:views) returns an array of constraints, and not just a single constraint.

    Since iOS8, it is recommended to activate constraints instead of adding them to a view. For a single constraint, you can just set its isActive property to true, and iOS will add that constraint to the proper view to active it.

    For multiple constraints, use NSLayoutConstraint.activate to activate the constraints instead of adding them to the view:

    NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|-16-[v0]-16-|", metrics: nil, views: ["v0":thumbnailImageView]))
    NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:|-16-[v0]-16-|", metrics: nil, views: ["v0":thumbnailImageView]))