Last active
March 1, 2023 18:15
-
-
Save IanKeen/ac051da0eeeaefcae9cbb8c1e4bb9c1b to your computer and use it in GitHub Desktop.
Lightweight styling setup using UIAppearance
This file contains hidden or 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 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 |
This file contains hidden or 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
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