Created
May 12, 2018 11:41
-
-
Save rpassis/ecff639555415e84e10a0b2121bd93b2 to your computer and use it in GitHub Desktop.
Swift - Stylesheet
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
struct Style<View: UIView> { | |
private let style: (View) -> Void | |
init(style: @escaping (View) -> Void) { | |
self.style = style | |
} | |
func apply(to view: View) { | |
style(view) | |
} | |
} | |
extension UIView { | |
convenience init<V>(style: Style<V>) { | |
self.init(frame: .zero) | |
apply(style) | |
} | |
func apply<V>(_ style: Style<V>) { | |
guard let view = self as? V else { | |
print("💥 Could not apply style for \(V.self) to \(type(of: self))") | |
return | |
} | |
style.apply(to: view) | |
} | |
} | |
let style = Style<UIView> { | |
$0.backgroundColor = .red | |
$0.translatesAutoresizingMaskIntoConstraints = false | |
} | |
let frame = CGRect(x: 0, y: 0, width: 500, height: 500) | |
let view = UIView(style: style) | |
view.frame = frame | |
let label = UILabel(style: style) | |
label.text = "Test" | |
label.sizeToFit() | |
view.addSubview(label) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment