Search code examples
iosswiftnslayoutconstraintprogrammatically-created

NSLayoutConstraints error


I like to layout constraints in code.. but for some reason my latest swift project is throwing errors my way.. my constraint code is this.

    let views = ["optionsView":optionsView, "cameraView":cameraView, "imageView":imageView]
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-[optionsView(300)]-[cameraView(300)]-[imageView(300)]", options: NSLayoutFormatOptions(0), metrics: nil, views: views))
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[optionsView(500)]", options: NSLayoutFormatOptions(0), metrics: nil, views: views))
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[cameraView(500)]", options: NSLayoutFormatOptions(0), metrics: nil, views: views))
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[imageView(500)]", options: NSLayoutFormatOptions(0), metrics: nil, views: views))

For all four constraints, Xcode throws an error, telling me that the last function parameter - views - is invalid. The error message is thus:

'String' is not identical to 'NSObject'

any ideas?? plz and thank you


Solution

  • The problem is NSLayoutFormatOptions(0). Just say nil.

    Oh, also, all your views are Optionals. You need to unwrap all of them!

    let views = ["optionsView":optionsView!, "cameraView":cameraView!, "imageView":imageView!]