IOS developer based in barcelona.

Stylesheet - consistency in your style guide

One important thing I always do when I start an app is creating a Stylesheet. In this Stylesheet is defined all the contracts with the designer team: colors, fonts, paddings, and so on. So, instead of adding a hardcoded color like

view.backgroundColor = UIColor.gray

A nice way to do that is with enums:

view.backgroundColor = Stylesheet.color(.mainLightGray)

There are a lot of benefits doing that, but the most important for me is the single source of truth.

In the next lines, I will show you an easy way to create some "rules" to use in our design. The first step is to create a contract

protocol Stylesheetable {
    static func font(_ font: Font) -> UIFont
    static func color(_ color: Color) -> UIColor
}

To keep simplicity, our Stylesheet only will have fonts and colors, the next step is to create all the cases for all colors that we want to use:

enum Color {
    case mainGray
    case mainLightGray
    case mainBlue
    case white
    case black
}

And also, we need another enum to display fonts:

enum Font {
    case light
    case bold
    case italic
}

And that's it! now our struct needs to conform our Stylesheetable protocol, and declare all the cases for Color and Font

struct Stylesheet: Stylesheetable {
    static func font(_ font: Font) -> UIFont {
        switch font {
        case .light:
            return UIFont(name: "HelveticaNeue-Light", size: 20)!
        case .bold:
            return UIFont(name: "HelveticaNeue-Bold", size: 20)!
        case .italic:
            return UIFont(name: "HelveticaNeue-Italic", size: 20)!
        }
    }
    
    static func color(_ color: Color) -> UIColor {
        switch color {
        case .mainGray:
            return UIColor(colorLiteralRed: 144/255.0, green: 146/255.0, blue: 165/255.0, alpha: 1.0)
        case .mainLightGray:
            return UIColor(colorLiteralRed: 247/255.0, green: 247/255.0, blue: 247/255.0, alpha: 1.0)
        case .mainBlue:
            return UIColor(colorLiteralRed: 49/255.0, green: 165/255.0, blue: 236/255.0, alpha: 1.0)
        case .white:
            return UIColor.white
        case .black:
            return UIColor.black
        }
    }
}

Now, you can try a playground to use our code

let rect = CGRect(x: 0, y: 0, width: 200, height: 100)
let label = UILabel(frame: rect)
label.textAlignment = .center
label.font = Stylesheet.font(.bold)
label.textColor = Stylesheet.color(.white)
label.text = "Hello, Alberto!"
Screen Shot 2017-07-16 at 21.43.46.png

If we change the font and color:

label.font = Stylesheet.font(.light)
label.textColor = Stylesheet.color(.mainBlue)

Conclusion

With this simple tip you can create a robust style guide for your app. New co-workers can easily interact with the Stylesheet instead of adding hardcoded values.

I'm all ears to know your feedback, thanks for reading! 😃

Playgrounds - great for prototyping views