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
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...
There are probably a thousand different ways to do this, but I use the following extension:
extension UIColor {
convenience init(rgb: UInt) {
self.init(
red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgb & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
Then you can set the color of any object using the common HEX color code of RGB colors. Quickly find HEX colors here: http://www.color-hex.com/
view.backgroundColor = UIColor(rgb: 0xFF0000)
will set the backgroundColor of view to red.
Hope this helps
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.