Skip to content

Instantly share code, notes, and snippets.

@rikschennink
Last active November 8, 2019 14:38
Show Gist options
  • Save rikschennink/b0cee7e89e5257ee8bdc to your computer and use it in GitHub Desktop.
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.
// 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
})
// 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)
}
}
}
@rikschennink
Copy link
Author

You can link styles to UI elements with the style property (in code or on storyboard).

var buttonBuyProduct = UIButton()
buttonBuyProduct.style = "btn-default btn-attention"

As a front-end developer used to styling UI elements with CSS I was really missing something similar in Swift.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment