Swift 错误中的 UIColor 扩展 [英] UIColor extension in Swift error

查看:34
本文介绍了Swift 错误中的 UIColor 扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个扩展:

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 is giving me an error message: Extra argument 'green' in call

我不明白为什么会这样,可能是 xcode 6 beta 4 或 swift 中的错误.

I dont get why this is happening, might be a bug in xcode 6 beta 4 or in swift.

推荐答案

这是因为你传递的所有参数类型错误:r/255, g/255, b/255 are Integer anda 是 Fl​​oat,但 UIColor 的 init 方法接受 CGFloat 作为 4 个参数.

It is because you passed all the parameters with wrong type: r/255, g/255, b/255 are Integer and a is Float, but the UIColor's init method accepts CGFloat for the 4 parameters.

修改代码为:

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))
}

这篇关于Swift 错误中的 UIColor 扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆