Skip to content

Instantly share code, notes, and snippets.

@IanKeen

IanKeen/Example.swift

Last active Feb 5, 2020
Embed
What would you like to do?
Lightweight styling setup using UIAppearance
import PlaygroundSupport
// using constrained static members on `Style` we can create presets
extension Style where T: UIButton {
static var global: Style<UIButton> {
return .init { button in
button.backgroundColor = .blue
button.setTitleColor(.red, for: .normal)
}
}
static var local: Style<UIButton> {
return .init { button in
button.backgroundColor = .green
}
}
}
// apply style to _all_ instances of UIButton
UIButton.styleAll(with: .global)
let view = UIView(frame: .init(x: 0, y: 0, width: 300, height: 500))
view.backgroundColor = .red
// apply style _only_ to this instance - notice that the styles have composed!
let button = UIButton(frame: .init(x: 25, y: 25, width: 250, height: 50)).styled(with: .local)
button.setTitle("Test", for: .normal)
view.addSubview(button)
PlaygroundPage.current.liveView = view
protocol Styleable: class { }
extension UIView: Styleable { }
extension Styleable where Self: UIView {
func style(_ closure: (Self) -> Void) -> Self {
closure(self)
return self
}
func styled(with style: Style<Self>) -> Self {
return self.style(style.applyStyle)
}
static func styleAll(_ closure: (Self) -> Void) {
closure(appearance())
}
static func styleAll(with style: Style<Self>) {
style.applyStyle(appearance())
}
}
struct Style<T: UIView> {
let applyStyle: (T) -> Void
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.