Search code examples
swiftuipickerviewuicolor

UIColor initializer (cannot find an initializer of type 'UIColor' that accepts ....) error


I know it is not an appropriate way to do this but for the purpose of learning I have a picker control with four components and 255 rows in each to change the 'view' background color based on RGB-alpha. I know UIColor(red: <#CGFloat#>, green: <#CGFloat#>, blue: <#CGFloat#>, alpha: <#CGFloat#>) accepts four float numbers as parameter for each color but I get the error:
Cannot find an initializer for type 'UIColor' that accepts an argument list of type '(red: Float, green: Float, blue: Float, alpha: Float)'
What is wrong?

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    var newbackgroundColor = UIColor()

    var redCode: Float = 0.0
    var greenCode: Float = 0.0
    var blueCode: Float = 0.0
    var alphaCode: Float = 0.0

    if component == 0 {
        switch row {
        case 0..<256:
            redCode = Float(row/255)
            newbackgroundColor = UIColor(red: redCode, green: greenCode, blue: blueCode, alpha: alphaCode)
        default:
            break
        }

    } else if component == 1 {
        switch row {
        case 0..<256:
            greenCode = Float(row/255)
            newbackgroundColor = UIColor(red: redCode, green: greenCode, blue: blueCode, alpha: alphaCode)
        default:
            break
        }

    } else if component == 2{
        switch row {
        case 0..<256:
            blueCode = Float(row/255)
            newbackgroundColor = UIColor(red: redCode, green: greenCode, blue: blueCode, alpha: alphaCode)
        default:
            break
        }

    } else {
        switch row {
        case 0..<256:
            alphaCode = Float(row/255)
            newbackgroundColor = UIColor(red: redCode, green: greenCode, blue: blueCode, alpha: alphaCode)
        default:
            break
        }

    }

    self.view.backgroundColor = newbackgroundColor
}

Solution

  • Use CGFloat not Float

    Check the API docs when you get an error like this