Skip to content

Instantly share code, notes, and snippets.

@schpaa
Last active February 9, 2016 09:20
Show Gist options
  • Save schpaa/d1ad2feddd900ed70c06 to your computer and use it in GitHub Desktop.
Save schpaa/d1ad2feddd900ed70c06 to your computer and use it in GitHub Desktop.
Constraints registering in Swift
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
@aceontech
Copy link

Really cool! Was bummed out to find out CAConstraint is not available on iOS.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment