I've been using this macro in Objective-C:
#define RGBA(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)]
I am trying to figure out how I can get the closest thing possible in swift. Any ideas?
I've been using this macro in Objective-C:
#define RGBA(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)]
I am trying to figure out how I can get the closest thing possible in swift. Any ideas?
An extension on UIColor is a valid option.
extension UIColor {
convenience init(_ r: Double, _ g: Double, _ b: Double, _ a: Double) {
self.init(red: r/255, green: g/255, blue: b/255, alpha: a)
}
}
Usage
let white = UIColor(255.0, 255.0, 255.0, 1.0)
_ allows you to skip the parameter names when calling the methods.In the global scope provide:
func RGBA (r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat) {
return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a)
}
and then use it with:
var theColor : UIColor = RGBA (255, 255, 0, 1)
What I did is to create a class method that returns the #define.
Example:
.h file
#define RGBA(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)]
+ (UIColor*)RGBA:(CGFloat)r g:(CGFloat)g b:(CGFloat)b a:(CGFloat)a;
.m file
+ (UIColor*)RGBA:(CGFloat)r g:(CGFloat)g b:(CGFloat)b a:(CGFloat)a { return RGBA(r, g, b, a); }