iosswiftvisual-format-language

Problems with Layout Constraints: NSArray is not a subtype of NSLayoutConstraint


I seem to be having issues with NSLayoutConstraint. From what I can gather (and I hope I am wrong here), the .addConstrait() function is supposed to take variable of type NSLayoutContraint - but NSLayoutConstraint.constraintsWithVisualFormat() is generating NSArrays?

This doesnt make sense to me. Ive tried translating the NSArray over to a NSLayoutConstraint but I get errors doing that. Surely the output from NSLayoutConstraint.constraintsWithVisualFormat() would be the same type as is expected by .addConstrait()??

If not why not? and what is the best way to solve this issue?

Here is the code:

    let swiftViews:Dictionary[String: UIView] = ["status":status]
    let swiftMetrics = ["standardWidth":200]
    let views:NSDictionary = swiftViews as NSDictionary
    let metrics:NSDictionary = swiftMetrics as NSDictionary

    let statusHorzVFLCons = NSLayoutConstraint.constraintsWithVisualFormat("|-[status]-|", options: NSLayoutFormatOptions(0), metrics: metrics, views: views)

    self.view.addConstraint(statusHorzVLFCons)

This last line produces the error:

'NSArray' is not a subtype of 'NSLayoutConstraint'

Can someone point out where I am going wrong.


Solution

  • constraintsWithVisualFormat(_:options:metrics:views:) returns NSArray of NSLayoutConstraint.

    Just use addConstraints(_:) instead of addConstraint(_:)

    self.view.addConstraints(statusHorzVLFCons)
                           ^