Created
September 6, 2014 23:22
-
-
Save chrisschreiner/daeaeec158e3693e1d9d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
internal class BaseCALayer { | |
private var layer: CALayer | |
private var _constraint:[Constraint.T]? | |
private var constraint:[Constraint.T] { | |
set(newValue) | |
{ | |
Constraint.process(newValue,layer) | |
} | |
get | |
{ | |
return _constraint! | |
} | |
} | |
init() { | |
layer = CALayer() | |
} | |
} | |
//MARK:- here's the core idea, use the typed tuple as a container and massage it into a layer | |
class LayerB: BaseCALayer { | |
override init() { | |
super.init() | |
layer.name = "layerB" | |
layer.bounds = CGRectMake(0,0,300,60) | |
layer.borderWidth = 2.0 | |
layer.backgroundColor = NSColor.redColor().CGColor | |
constraint = [ | |
(.Width, "layerA", .Width, 0), | |
(.MidX, "layerA", .MidX, 0), | |
(.MaxY, "layerA", .MinY, -10), | |
(.MinY, "superlayer", .MinY, +10)] | |
} | |
} | |
class LayerC : BaseCALayer { | |
override init() { | |
super.init() | |
layer.name = "layerC" | |
layer.bounds = CGRectMake(0,0,40,40) | |
layer.borderWidth = 4.0 | |
layer.backgroundColor = NSColor.yellowColor().CGColor | |
constraint = [ | |
(.MinX, "layerB", .MaxX, +10), | |
(.MaxY, "layerA", .MinY, -10)] | |
} | |
} | |
//MARK:- etc... | |
class LayerA: BaseCALayer { | |
override init() { | |
super.init() | |
layer.name = "layerA" | |
layer.bounds = CGRectMake(0,0,200,125) | |
layer.borderWidth = 2.0 | |
layer.backgroundColor = NSColor.greenColor().CGColor | |
constraint = [ | |
(.MidY, "superlayer", .MidY, 0), | |
( .MidX, "superlayer", .MidX, 0)] | |
} | |
} | |
layer.addSublayer(LayerC().layer) | |
layer.addSublayer(LayerA().layer) | |
layer.addSublayer(LayerB().layer) | |
view.layer = layer | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment