Skip to content

Instantly share code, notes, and snippets.

@divyeshmakwana96
Created July 19, 2019 19:07
Show Gist options
  • Save divyeshmakwana96/22ddbf21b3985d78c65722ec1e997b67 to your computer and use it in GitHub Desktop.
Save divyeshmakwana96/22ddbf21b3985d78c65722ec1e997b67 to your computer and use it in GitHub Desktop.
UIStackView custom spacing extension
import UIKit
extension UIStackView {
struct Spacer {
var space: CGFloat = 0
init(_ space:CGFloat) {
self.space = space
}
}
var count: Int {
return arrangedSubviews.count
}
var lastArrangedSubview: UIView? {
if count > 0 {
return arrangedSubviews[count-1]
} else {
return nil
}
}
func setArrangedSubviews(_ subviews: [Any]) {
removeAllArrangedSubviews()
var index = 0
for view in subviews {
if let view = view as? UIView {
insertArrangedSubview(view, at: index)
index += 1
} else {
if let spacer = view as? Spacer, let last = lastArrangedSubview {
setCustomSpacing(spacer.space, after: last)
}
}
}
}
func removeAllArrangedSubviews() {
for subview in arrangedSubviews {
subview.removeFromSuperview()
}
}
}
@divyeshmakwana96
Copy link
Author

divyeshmakwana96 commented Jul 19, 2019

Usage:

stackView.setArrangedSubviews([view1, Spacer(20), view2, Spacer(10), view3])

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