Using Autolayout Visual Format with Swift?

后端 未结 9 1963
执笔经年
执笔经年 2021-02-01 14:57

I\'ve been trying to use the Autolayout Visual Format Language in Swift, using NSLayoutConstraint.constraintsWithVisualFormat. Here\'s an example of some code that

相关标签:
9条回答
  • 2021-02-01 15:53

    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

    • Cartography, which is a new approach, but quite awesome. It uses Autolayout under the hood.
    • SnapKit, which I haven't tried but is also a DSL autolayout framework
    0 讨论(0)
  • 2021-02-01 15:58

    this works for me with no error:

    let bar:[AnyObject]! = NSLayoutConstraint.constraintsWithVisualFormat(
      nil, options: NSLayoutFormatOptions(0), metrics: nil, views: nil)
    

    update

    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])
    

    update

    (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!

    0 讨论(0)
  • 2021-02-01 15:58

    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)
    
    0 讨论(0)
提交回复
热议问题