Where do you make the global method fast?

I have a function that is common to all of my controllers:

func myColor() -> UIColor {
    return UIColor(red: 9.0/255.0, green: 134.0/255.0, blue: 255.0/255.0, alpha: 1)
}

      

Where can I put this function so that I can access it from any controller?

+3


source to share


3 answers


By default, all default access functions ( internal

) are available throughout the application. If you have this function defined in another module, you need to use the modifier public

.

To make the code clearer, it's better to create an extension for UIColor

.

extension UIColor {
    class func myColor() -> UIColor {
        return UIColor(red: 9.0/255.0, green: 134.0/255.0, blue: 255.0/255.0, alpha: 1)
    }
}

      



Then you can use the myColor

same as default colors UIColor

.

let systemColor = UIColor.blackColor()
let myColor = UIColor.myColor()

      

+5


source


1) Is your function returning the same color every time as in the question? In such a case, why don't you make it a static color in the AppDelegate, which you can access anywhere using

(UIApplication.sharedApplication() as AppDelegate).myColor

      

2) If your color will return a different color every time based on your class properties but use the same formula for all classes eg.

func myColor() -> UIColor {
    return UIColor(red: (prop1 * 5)/255.0, green: prop2/255.0, blue: (prop3/2)/255.0, alpha: 1)  
}

      



you can define prop1, prop2, prop3 and a function in the base class, which each class can override and set its own property values. The function does not need to be redefined.

3) If the formula for calculating the color is different for each class, you can try to create a protocol that defines this function and properties. Each class that inherits from this property will need to provide its own implementation of the formula.

You can choose the right solution based on your needs.

I hope this helped!

+3


source


Add the swift filename UIColorExt.swift :

import UIKit        
class func RGB(r: CGFloat, _ g: CGFloat, _ b: CGFloat, _ alpha: CGFloat = 1.0) -> UIColor{
   return UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: alpha)
}

      

Using:

view.backgroundColor = UIColor.RGB(204, 119, 70)

      

0


source







All Articles