Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to introduce a custom UIColor to a Swift project? [closed]

Tags:

ios

swift

uicolor

I've thought of two types of implementation; which one of them is better in your opinion in terms of performance, readability and maintainability?

  1. Create an extension of UIColor like this

    extension UIColor {
        class func myColor() -> UIColor {
            return UIColor(red: 128/255, green: 102/255, blue: 0, alpha: 1)
        }
    }
    
  2. Create a structure:

    struct Colors {
        static let myColor = UIColor(red: 255/255, green: 102/255, blue: 0, alpha: 1)
    }
    
like image 693
javal88 Avatar asked Mar 29 '16 11:03

javal88


2 Answers

Answer: Extension, in my professional opinion.

Think about it; you are, in philosophy, 'extending' the range of colors offered by UIColor. Provided that your color name is distinct and the new function follows Apple's method naming protocol (i.e. <color name>Color), extending UIColor seems neater. One or two new colors (in my opinion) don't warrant an entire dedicated struct.


Bonus answer: Where would a struct (or enum!) be a good fit?

  • If your app forces replacements for the standard colors (i.e. custom 'primary' colors)
  • If your app is specifically designed to be themed / customized, it might be good have an enum, to serve as a concrete list for available options.
  • If you can't think of standard names for the colors (sharkBlueColor, anyone?).
  • If your app is specifically for drawing/painting (in which case a 'palette' construct might be good idea).

... the list goes on. You must learn to discern and decide for yourself as you mature as a Swift developer!

like image 100
Vatsal Manot Avatar answered Oct 11 '22 19:10

Vatsal Manot


I use enums for this

enum AppColor: UInt32 {

    case DarkBlue = 0x00437C
    case LightBlue = 0x7CCEF0

    var color: UIColor {
        return UIColor(hex: rawValue)
    }

}

This way it is easy to reuse same color in xib/storyboard because I have hex values ready for copy/paste. And also less code needed for defining new color

For creating colors from hex value I used UIColor extension:

extension UIColor {

    public convenience init(hex: UInt32) {
        let mask = 0x000000FF

        let r = Int(hex >> 16) & mask
        let g = Int(hex >> 8) & mask
        let b = Int(hex) & mask

        let red   = CGFloat(r) / 255
        let green = CGFloat(g) / 255
        let blue  = CGFloat(b) / 255

        self.init(red:red, green:green, blue:blue, alpha:1)
    }

}
like image 32
Silmaril Avatar answered Oct 11 '22 21:10

Silmaril