6

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?

3
  • How about making a function that wraps around Swift's syntax for creating a color, if it's too long for you? Commented Jun 13, 2014 at 23:05
  • 4
    In Swift, Apple has decided that macros make debugging harder. They want you to use a function instead. Commented Jun 13, 2014 at 23:08
  • ok, so no more macros. I see. thanks for the input Commented Jun 13, 2014 at 23:11

3 Answers 3

9

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)
Sign up to request clarification or add additional context in comments.

3 Comments

This works thanks. Will this be visible to other classes now?, also, why did you add the "_" before each parameter in the function call?
the _ allows you to skip the parameter names when calling the methods.
It might be just a swift 2.0 issue but you need to add CGFloat convert on the double values other wise you'll get an error that a double is not convertible to CGFloat
8

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)

3 Comments

I'll try this. I am not 100% sure I understand it, could you provide the full answer in code? thank you
Yes, but check out the Apple documentation for UIColor, specifically the init() functions with their Swift calling convention.
So I added what you suggested: func RGBA (r:Int, g:Int, b:Int, a:Int) -> UIColor { return UIColor(red:r/255.0,green:g/255.0,blue:b/255.0,alpha:a) } and also added the Return type -> UIColor. Compiler gave me an error saying: "Could not find an overload for '/' that accepts the supplied arguments. The initializer in UIColor cannot take in Int, so I went ahead and changed the "Int" to "CGFloat" and it worked. I will mark @Gabriele Petronella's answer correct as it worked as is. Thank you.
0

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); }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.