Last active
February 28, 2021 17:14
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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