Last active
August 29, 2015 14:15
-
-
Save truppelito/24fe8adaf1d997d49a90 to your computer and use it in GitHub Desktop.
Use Cartography to layout equally spaced views
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
func pairs<C: CollectionType>(source: C, block: (C.Generator.Element, C.Generator.Element) -> ()) { | |
var last: C.Generator.Element? | |
for i in source { | |
if let l = last { | |
block(l, i) | |
} | |
last = i | |
} | |
} | |
func distributeHorizontallyWithEqualSpacing(views: UIView...) { | |
let spacers = (1..<views.count).map { _ in UIView() } | |
for v in spacers { views.first!.superview!.addSubview(v) } | |
// I'm sure there's a functional programming function just for this... | |
var spacersAndViews = [UIView]() | |
for i in 0..<(views.count + spacers.count) { | |
if i % 2 == 0 { spacersAndViews += [views[i/2]] } | |
else { spacersAndViews += [spacers[(i-1)/2]] } | |
} | |
constrain(spacersAndViews) { views in | |
pairs(views) { $0.right == $1.left; return } | |
} | |
constrain(spacers) { views in | |
pairs(views) { $0.width == $1.width; return } | |
for v in views { | |
v.height == 1 | |
v.top == v.superview!.top | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Unfortunately, Xcode wouldn't let me test this because it was crashing every 2 minutes and wouldn't compile not even a single line of Swift code. If anything doesn't work, feel free to leave a comment here.