Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save iosdevzone/985340046154d290e7e9c22390efb6d7 to your computer and use it in GitHub Desktop.
Save iosdevzone/985340046154d290e7e9c22390efb6d7 to your computer and use it in GitHub Desktop.
UIViewBuilder syntactic sugar
import UIKit
///
///Declaration
///
protocol UIViewBuilder: AnyObject {}
extension UIViewBuilder where Self: UIView {
init(_ build: ((Self) -> Void)) {
self.init()
build(self)
}
}
extension UIViewBuilder {
func configure(_ build: ((Self) -> Void)) -> Self {
build(self)
return self
}
}
extension UIView: UIViewBuilder {}
extension UIViewController: UIViewBuilder {}
/// ViewController components creation
class ViewController: UIViewController {
let coloredSubView = UIView {
$0.backgroundColor = .orange
}
let button = UIButton(type: .system).configure {
$0.backgroundColor = .orange
$0.setTitle("Action", for: .normal)
}
}
///Preview usefull for prototyping
#Preview {
UIButton(type: .system).configure {
$0.backgroundColor = .orange
$0.setTitle("Action", for: .normal)
}
}
/// Functional components composition example
#Preview {
UIStackView { stack in
stack.addArrangedSubview(UIButton(type: .system).configure {
$0.backgroundColor = .red
$0.setTitle("Red", for: .normal)
})
stack.addArrangedSubview(UIButton(type: .system).configure {
$0.backgroundColor = .yellow
$0.setTitle("Yellow", for: .normal)
})
stack.addArrangedSubview(UIButton(type: .system).configure {
$0.backgroundColor = .green
$0.setTitle("Green", for: .normal)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment