Using Autolayout Visual Format with Swift?

后端 未结 9 1979
执笔经年
执笔经年 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

提交回复
热议问题