Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
851 views
in Technique[技术] by (71.8m points)

ios - 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 UIColor.whiteColor() when this error occurs. Of course, if I explicitly call this function, error occurs still!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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(red: Int = 0, green: Int = 0, blue: Int = 0, opacity: Int = 255) {
        precondition(0...255 ~= red   &&
                     0...255 ~= green &&
                     0...255 ~= blue  &&
                     0...255 ~= opacity, "input range is out of range 0...255")
        self.init(red: CGFloat(red)/255, green: CGFloat(green)/255, blue: CGFloat(blue)/255, alpha: CGFloat(opacity)/255)
    }
}

UIColor(red: 255)               // r 1.0 g 0.0 b 0.0 a 1.0  (Red)
UIColor(red: 255, green: 255)   // r 1.0 g 1.0 b 0.0 a 1.0  (Yellow)
UIColor(red: 255, blue: 255)    // r 1.0 g 0.0 b 1.0 a 1.0  (Magenta)

UIColor(green: 255)             // r 0.0 g 1.0 b 0.0 a 1.0  (Green)
UIColor(green: 255, blue: 255)  // r 0.0 g 1.0 b 1.0 a 1.0  (Cyan)

UIColor(blue: 255)              // r 0.0 g 0.0 b 1.0 a 1.0  (Blue)
UIColor(red: 255, green: 192, blue: 203)  // r 1.0 g 0.753 b 0.796 a 1.0 (Pink)
UIColor(red: 255, green: 215)   // r 1.0 g 0.843 b 0.0 a 1.0 (Gold)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...