Expanding UIColor on Swift error
I have this extension:
extension UIColor {
func rgba(r: Int, g: Int, b: Int, a: Float) -> UIColor {
return UIColor(red: r/255, green: g/255, blue: b/255, alpha: a)
}
}
This gives me an error: Extra argument 'green' in call
I don't understand why this is happening, there might be a bug in xcode 6 beta 4 or in swift.
+3
Arbitur
source
to share
3 answers
This is because you passed all parameters with the wrong type: r/255, g/255, b/255
- Integer and a
- Float, but the init method of UIColor accepts CGFloat for 4 parameters.
Change your code to:
func rgba(r: Int, g: Int, b: Int, a: Float) -> UIColor {
let floatRed = CGFloat(r) / 255.0
let floatGreen = CGFloat(g) / 255.0
let floatBlue = CGFloat(b) / 255.0
return UIColor(red: floatRed, green: floatGreen, blue: floatBlue, alpha: CGFloat(a))
}
+8
Louis Zhu
source
to share
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)
+3
Leo dabus
source
to share
Try the following:
extension UIColor {
class func rgba(r: Int, g: Int, b: Int, a: Float) -> UIColor {
return UIColor(red: r/255, green: g/255, blue: b/255, alpha: a)
}
}
+1
Alex
source
to share