I\'ve been trying to use the Autolayout Visual Format Language in Swift, using NSLayoutConstraint.constraintsWithVisualFormat
. Here\'s an example of some code that
This works with Xcode 6.1.1:
extension NSView {
func addConstraints(constraintsVFL: String, views: [String: NSView], metrics: [NSObject: AnyObject]? = nil, options: NSLayoutFormatOptions = NSLayoutFormatOptions.allZeros) {
let mutableDict = (views as NSDictionary).mutableCopy() as NSMutableDictionary
let constraints = NSLayoutConstraint.constraintsWithVisualFormat(constraintsVFL, options: options, metrics: metrics, views: mutableDict)
self.addConstraints(constraints)
}
}
Then you can use calls like:
var views : [String: NSView] = ["box": self.box]
self.view.addConstraints("V:[box(100)]", views: views)
This works to add constraints. If you are using iOS, substitute UIView
for NSView
You should probably check out
this works for me with no error:
let bar:[AnyObject]! = NSLayoutConstraint.constraintsWithVisualFormat(
nil, options: NSLayoutFormatOptions(0), metrics: nil, views: nil)
the line above may not be compiled since the 1st and 4th parameters cannot be optionals anymore.
syntactically those have to be set, like e.g. this:
let bar:[AnyObject] = NSLayoutConstraint.constraintsWithVisualFormat("", options: NSLayoutFormatOptions(0), metrics: nil, views: ["": self.view])
(for Xcode 7, Swift 2.0)
the valid syntax now requests the parameters's name as well, like:
NSLayoutFormatOptions(rawValue: 0)
NOTE: this line of code shows the correct syntax only, the parameters itself won't guarantee the constraint will be correct or even valid!
Try this - remove the initial variable name (format:
), use NSLayoutFormatOptions(0)
, and just pass nil
for those optional NSDictionaries:
let foo:[AnyObject]! = NSLayoutConstraint.constraintsWithVisualFormat("", options: NSLayoutFormatOptions(0), metrics: nil, views: nil)