Skip to content

Instantly share code, notes, and snippets.

@chrisschreiner
Created September 5, 2014 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisschreiner/db32cde87300c0e76017 to your computer and use it in GitHub Desktop.
Save chrisschreiner/db32cde87300c0e76017 to your computer and use it in GitHub Desktop.
Writing succinct constraints
import Cocoa
struct Constraint {
typealias T = (attribute: CAConstraintAttribute, relativeTo:String, relatedAttribute: CAConstraintAttribute, offset: CGFloat)
let data: T
func create() -> CAConstraint {
let newConstraint: AnyObject! = CAConstraint.constraintWithAttribute(data.attribute, relativeTo: data.relativeTo, attribute: data.relatedAttribute, offset: data.offset)
return newConstraint as CAConstraint
}
static func process(list:[T], _ layer:CALayer) {
for each in list {
let c = Constraint(data:each).create()
layer.addConstraint(c)
}
}
}
var r = CGRectMake(0,0,300,300)
var view = NSView(frame:r)
var layer = CALayer()
layer.layoutManager = CAConstraintLayoutManager()
//MARK:- You can now create a layer and define constraints in a succinct manner
var layerB = CALayer()
layerB.name = "layerB"
layerB.bounds = CGRectMake(0,0,300,60)
layerB.borderWidth = 2.0
layerB.backgroundColor = NSColor.redColor().CGColor
//MARK:- here's the core idea, use the typed tuple as a container and massage it into a layer
var layerB_Constraints:[Constraint.T] = [
(.Width, "layerA", .Width, 0),
(.MidX, "layerA", .MidX, 0),
(.MaxY, "layerA", .MinY, -10),
(.MinY, "superlayer", .MinY, +10)]
Constraint.process(layerB_Constraints,layerB)
//MARK:- etc…
var layerA = CALayer()
layerA.name = "layerA"
layerA.bounds = CGRectMake(0,0,200,125)
layerA.borderWidth = 2.0
layerA.backgroundColor = NSColor.greenColor().CGColor
Constraint.process([(.MidY, "superlayer", .MidY, 0), ( .MidX, "superlayer", .MidX, 0)], layerA)
layer.addSublayer(layerA)
layer.addSublayer(layerB)
view.layer = layer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment