Last active
November 8, 2019 14:38
-
-
Save rikschennink/b0cee7e89e5257ee8bdc to your computer and use it in GitHub Desktop.
A UIView extension that adds a style property which allows you to style UI elements using tags.
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
// Default button style | |
StyleCollection.addStyle("btn-default", paint: {(view) -> Void in | |
// These buttons should all have rounded corners and a dropshadow | |
view.layer.cornerRadius = view.frame.height * 0.5 | |
view.layer.backgroundColor = UIColor(hex:0x294A5F).CGColor | |
view.layer.shadowColor = UIColor.blackColor().CGColor | |
view.layer.shadowOffset = CGSizeMake(0, 2) | |
view.layer.shadowRadius = 2 | |
view.layer.shadowOpacity = 0.15 | |
if let button = view as? UIButton { | |
button.setTitleColor(UIColor.whiteColor(), forState: .Normal) | |
} | |
}) | |
// Attention button style | |
StyleCollection.addStyle("btn-attention", paint: {(view) -> Void in | |
// These buttons should feature a more -in your face- background color | |
view.layer.backgroundColor = UIColor(hex:0xEE638B).CGColor | |
}) |
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
// Collection of defined styles | |
private var styles:Dictionary<String,((view:UIView) -> Void)> = Dictionary() | |
// StyleCollection class | |
class StyleCollection { | |
class func addStyle(style:String, paint:((view:UIView) -> Void)) -> Void { | |
styles[style] = paint | |
} | |
class func applyStyle(style:String?, view:UIView) -> Void { | |
if (style == nil) { | |
return | |
} | |
let styleList = style!.characters.split{$0 == " "}.map(String.init) | |
for style:String in styleList { | |
applyStyle(style, view:view) | |
} | |
} | |
private class func applyStyle(style:String, view:UIView) -> Void { | |
if let paint = styles[style] { | |
paint(view:view) | |
} | |
} | |
} | |
// Adds style property to UIView so styles can be applied | |
extension UIView { | |
@IBInspectable var style: String! { | |
get { | |
return nil | |
} | |
set(newValue) { | |
StyleCollection.applyStyle(newValue, view:self) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can link styles to UI elements with the
style
property (in code or on storyboard).As a front-end developer used to styling UI elements with CSS I was really missing something similar in Swift.