Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define custom colors Swift

I'm rewriting my app in Swift (yes, hooray) and I'm running into the following:

I inherited a class, of which the definition is (.h)

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface MWColor : NSObject

+ (UIColor *)gray;
+ (UIColor *)green;
+ (UIColor *)themeColor;


@end

In here, I define colors, that I can use throughout my project as such:

myView.backgroundColor = MWColor.gray()

Now, I want to do this in a proper Swift way.

What would be the best approach? Extensions?

Help me to be a good Swift citizen

like image 986
Sjakelien Avatar asked Mar 02 '18 15:03

Sjakelien


People also ask

What is define custom colour?

Definition: A specially formulated colour used together with black ink or in addition to the separation colours. * A spot or non-process colour e.g. solid purple, gold, silver. Related Terms: custom palette.

How do I use custom colors in Xcode?

Click the gear and New to make a new custom color palette. You can name it whatever you want. Then click the plus (+) button to add a new color and name it. Use the color picker tool to set the color.

How do I change colors in Swift?

Find the view or view controller you want to change the background color of. Open it up in the interface builder and open the Attributes Inspector. Find the background color field and set it to the color you want.

How do I add RGB color in Swift?

Just add the property ColorLiteral as shown in the example, Xcode will prompt you with a whole list of colors which you can choose. The advantage of doing so is lesser code, add HEX values or RGB. You will also get the recently used colors from the storyboard. this is Amazing !


1 Answers

You can add computed colours to UIColor in an extension like this...

extension UIColor {
    static var myRed: UIColor { 
        // define your color here
        return UIColor(...) 
    }
}

or even...

extension UIColor {
    static let myRed = UIColor(... define the color values here ...)
}

Then access it like...

let someColor: UIColor = .myRed

or

let otherColor = UIColor.myRed

This matches the way that standard colours are defined too..

UIColor.red
UIColor.yellow
UIColor.myRed

etc...

like image 58
Fogmeister Avatar answered Nov 15 '22 11:11

Fogmeister