Skip to content

Instantly share code, notes, and snippets.

@theffc
Last active February 28, 2021 17:14
Show Gist options
  • Save theffc/6940e371d009abf25d384da1e076cf76 to your computer and use it in GitHub Desktop.
Save theffc/6940e371d009abf25d384da1e076cf76 to your computer and use it in GitHub Desktop.
This is an extension on UIViews that make it possible to add subviews in a more declarative/hierarchical way.
import UIKit
public extension UIView {
@discardableResult
func subviews(@SubviewsBuilder _ subviews: () -> [UIView]) -> UIView {
subviews().forEach { self.customAddSubview($0) }
return self
}
private func customAddSubview(_ view: UIView) {
if let stack = self as? UIStackView {
stack.addArrangedSubview(view)
} else {
self.addSubview(view)
}
}
}
@_functionBuilder
public struct SubviewsBuilder {
public static func buildBlock(_ children: UIView...) -> [UIView] {
return children
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment