donkey donkey - 8 months ago 49
iOS Question

UIColor extension convenience init not working

convenience init(red:Int,green:Int,blue:Int,alpha:CGFloat) {
var red: CGFloat = CGFloat(red)/255.0
var green: CGFloat = CGFloat(green)/255.0
var blue: CGFloat = CGFloat(blue)/255.0
self.init(red:red, green:green, blue:blue, alpha:alpha)

I wrote the code above to give a more convenience way of declaring my custom uicolor. But somehow, it crashes my app by calling itself until stack overflows. What is wrong here?

Also, I just realised that I am not explicitly calling this init function. But rather I was calling
when this error occurs. Of course, if I explicitly call this function, error occurs still!


I don't see any inconvenience doing it just like this:

let myCustomColorHSBa = UIColor(hue: 120/360, saturation: 0.25 , brightness: 1.0 , alpha: 1)
let myCustomColorRGBa = UIColor(red: 191/255, green: 1, blue: 191/255, alpha: 1)

but if you really need one, you can do as follow:

extension UIColor {
    convenience init(r: Int, g:Int , b:Int , a: Int) {
        self.init(red: CGFloat(r)/255, green: CGFloat(g)/255, blue: CGFloat(b)/255, alpha: CGFloat(a)/255)
let myColor = UIColor(r: 255 , g: 255, b: 255, a: 255)