Last active
November 8, 2023 04:49
-
-
Save salabaha/355adb6c9b661c438f5286a77d592d3a to your computer and use it in GitHub Desktop.
UIViewBuilder syntactic sugar
This file contains 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 | |
/// | |
///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