Skip to content

Instantly share code, notes, and snippets.

@malonehedges
Created May 16, 2019 01:34
Show Gist options
  • Save malonehedges/85fe03249738abb2679aad4eccb2f202 to your computer and use it in GitHub Desktop.
Save malonehedges/85fe03249738abb2679aad4eccb2f202 to your computer and use it in GitHub Desktop.
func distributeViewsEvenly(views: [UIView], axis: NSLayoutConstraint.Axis) -> UIView {
let containerView = UIView()
for (index, view) in views.enumerated() {
let previousView = containerView.subviews.last
let isLastView = index == views.endIndex - 1
containerView.addSubview(view)
view.snp.makeConstraints { make in
switch axis {
case .horizontal:
make.top.bottom.equalToSuperview()
if index == 0 {
make.left.equalToSuperview()
} else {
make.left.equalTo(previousView!.snp.right)
}
if isLastView {
make.right.equalToSuperview()
}
case .vertical:
make.left.right.equalToSuperview()
if index == 0 {
make.top.equalToSuperview()
} else {
make.top.equalTo(previousView!.snp.bottom)
}
if isLastView {
make.bottom.equalToSuperview()
}
}
}
if !isLastView {
let spacerView = UIView()
containerView.addSubview(spacerView)
spacerView.snp.makeConstraints { make in
switch axis {
case .horizontal:
make.top.bottom.equalToSuperview()
make.left.equalTo(view.snp.right)
if previousView != nil {
make.width.equalTo(previousView!)
}
case .vertical:
make.left.right.equalToSuperview()
make.top.equalTo(view.snp.bottom)
if previousView != nil {
make.height.equalTo(previousView!)
}
}
}
}
}
return containerView
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment