Skip to content

Instantly share code, notes, and snippets.

@truppelito
Last active August 29, 2015 14:15
Show Gist options
  • Save truppelito/24fe8adaf1d997d49a90 to your computer and use it in GitHub Desktop.
Save truppelito/24fe8adaf1d997d49a90 to your computer and use it in GitHub Desktop.
Use Cartography to layout equally spaced views
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
}
}
}
@truppelito
Copy link
Author

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.

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