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
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.
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.
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.
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 !
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With