UIColor扩展方便init无法正常工作 [英] 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)
}
我写了上面的代码,以便更方便地声明我的自定义的UIColor。但不知何故,它通过调用自身崩溃我的应用程序直到堆栈溢出。这里有什么问题?
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?
另外,我刚才意识到我没有明确地调用这个init函数。但是,当发生此错误时,我正在调用 UIColor.whiteColor()
。当然,如果我明确地调用了这个函数,错误仍然会发生!
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!
推荐答案
我没有看到任何不便这样做这个:
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)
这篇关于UIColor扩展方便init无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!