Skip to content

Instantly share code, notes, and snippets.

@Tavernari
Created December 13, 2018 22:07
Show Gist options
  • Save Tavernari/e9ffa2c0f1643d4428128a7252b8d4c8 to your computer and use it in GitHub Desktop.
Save Tavernari/e9ffa2c0f1643d4428128a7252b8d4c8 to your computer and use it in GitHub Desktop.
Dynamic appearance
extension String {
func capitalizingFirstLetter() -> String {
return prefix(1).uppercased() + self.dropFirst()
}
mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
}
struct AppearenceStyle{
let component:String
var properties:[String:Any] = [:]
init(component:String) {
self.component = component;
}
mutating func add(property:String, withValue value:Any){
self.properties[property] = value
}
}
class AppearenceManager{
init(styles:[AppearenceStyle]){
for style in styles{
if let appearenceClass = NSClassFromString(style.component) as? AnyObject {
let appearence = getAppearenceReference(fromComponent: appearenceClass)!
self.applyStyle(appearence: appearence, styles: style.properties)
}
}
}
private func applyStyle(appearence:AnyObject, styles:[String:Any]){
for (property, value) in styles{
let selector = Selector("set\(property.capitalizingFirstLetter()):")
print(appearence, selector, value)
appearence.performSelector(onMainThread: selector, with: value, waitUntilDone: true)
}
}
private func getAppearenceReference(fromComponent:AnyObject)->AnyObject?{
let appearenceSelector = Selector("appearance")
return fromComponent.perform(appearenceSelector)?.takeUnretainedValue() as? AnyObject
}
}
//Usage
var uiLabelStyle = AppearenceStyle(component: "UILabel");
uiLabelStyle.add(property: "textColor", withValue: UIColor.blue);
uiLabelStyle.add(property: "backgroundColor", withValue: UIColor.yellow);
let styles = [uiLabelStyle]
let appearenceManager = AppearenceManager(styles: styles)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment