Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace a #define macro I used to have in Objective-C in SWIFT?

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?

like image 457
zumzum Avatar asked Jun 13 '14 23:06

zumzum


2 Answers

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)
like image 160
Gabriele Petronella Avatar answered Sep 18 '22 11:09

Gabriele Petronella


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)
like image 39
GoZoner Avatar answered Sep 20 '22 11:09

GoZoner