Skip to content

Instantly share code, notes, and snippets.

@billwang1990
Created March 16, 2016 07:47
Show Gist options
  • Save billwang1990/753702e059005a650a95 to your computer and use it in GitHub Desktop.
Save billwang1990/753702e059005a650a95 to your computer and use it in GitHub Desktop.
BABABLA
//: Playground - noun: a place where people can play
import XCPlayground
import UIKit
class VerticalEqualSpacingView :UIView {
var spacing:CGFloat = 0 {
didSet {
guard oldValue != spacing else { return }
self.equalSpacing.forEach({$0.constant = spacing})
}
}
var equalSpacing = [NSLayoutConstraint]()
override func addSubview(view: UIView) {
super.addSubview(view)
equalSpacing.forEach({self.removeConstraint($0)})
equalSpacing = calculateEqualSpacingConstraint()
}
override func layoutSubviews() {
super.layoutSubviews()
let totalHeight = subviews.map({$0.frame.height}).reduce(0, combine: +)
self.spacing = (self.frame.height - totalHeight) / CGFloat(subviews.count + 1)
}
func calculateEqualSpacingConstraint() -> [NSLayoutConstraint] {
var previous: (UIView, NSLayoutAttribute) = (self, .Top)
var constraints = [NSLayoutConstraint]()
subviews.forEach { (view) -> () in
let constraint = NSLayoutConstraint(item: view, attribute: .Top, relatedBy: .Equal, toItem: previous.0, attribute: previous.1, multiplier: 1, constant: spacing)
previous = (view, .Bottom)
self.addConstraint(constraint)
constraints.append(constraint)
}
return constraints
}
}
let container = VerticalEqualSpacingView(frame: CGRect(x: 0, y: 0, width: 300, height: 500))
container.backgroundColor = .whiteColor()
let labelA = UILabel(frame: .zero)
labelA.translatesAutoresizingMaskIntoConstraints = false
labelA.text = "Hello,world"
labelA.sizeToFit()
labelA.backgroundColor = UIColor.redColor()
labelA.heightAnchor.constraintEqualToConstant(100).active = true
container.addSubview(labelA)
let labelB = UILabel(frame: .zero)
labelB.translatesAutoresizingMaskIntoConstraints = false
labelB.text = "Sup"
labelB.sizeToFit()
labelB.backgroundColor = UIColor.redColor()
container.addSubview(labelB)
XCPlaygroundPage.currentPage.liveView = container
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment