Last active
February 9, 2016 09:20
-
-
Save schpaa/d1ad2feddd900ed70c06 to your computer and use it in GitHub Desktop.
Constraints registering in Swift
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 | |
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
Really cool! Was bummed out to find out
CAConstraint
is not available on iOS.