Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Last active March 1, 2023 18:15
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IanKeen/ac051da0eeeaefcae9cbb8c1e4bb9c1b to your computer and use it in GitHub Desktop.
Save IanKeen/ac051da0eeeaefcae9cbb8c1e4bb9c1b to your computer and use it in GitHub Desktop.
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: AnyObject { }
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